python实现的文件夹清理程序分享


Posted in Python onNovember 22, 2014

使用:

foldercleanup.py -d 10 -k c:\test\keepfile.txt c:\test

表示对c:\test目录只保留最近10天的子文件夹和keepfile.txt中指定的子文件夹。

代码:

import os

import os.path

import datetime

  

def getOption():

  from optparse import OptionParser

  

  des   = "clean up the folder with some options"

  prog  = "foldercleanup"

  ver   = "%prog 0.0.1"

  usage = "%prog [options] foldername"

  

  p = OptionParser(description=des, prog=prog, version=ver, usage=usage,add_help_option=True)

  p.add_option('-d','--days',action='store',type='string',dest='days',help="keep the subfolders which are created in recent %days% days")

  p.add_option('-k','--keepfile',action='store',type='string',dest='keepfile',help="keep the subfolders which are recorded in text file %keepfile% ")

  options, arguments = p.parse_args()

  

  if len(arguments) != 1:

    print("error: must input one directory as only one parameter ")

    return

  

  return options.days, options.keepfile, arguments[0] 
 

def preCheckDir(dir):

  if(not os.path.exists(dir)):

    print("error: the directory your input is not existed")

    return

  if(not os.path.isdir(dir)):

    print ("error: the parameter your input is not a directory")

    return

    

  return os.path.abspath(dir)

  

def isKeepByDay(dir, day):

  indays = False

  if( day is not None) :

    t = os.path.getctime(dir)

    today = datetime.date.today()

    createdate = datetime.date.fromtimestamp(t)

    indate = today - datetime.timedelta(days = int(day))

    print (createdate)

    if(createdate >= indate):

      indays = True

  print (indays)

  return indays

  

def isKeepByKeepfile(dir, keepfile):

  needkeep = False

  print (dir)

  if (keepfile is not None):

    try :

      kf = open(keepfile,"r")

      for f in kf.readlines():

        print (f)

        if (dir.upper().endswith("\\" + f.strip().upper())):

          needkeep = True

      kf.close()

    except:

      print ("error: keep file cannot be opened")

  print(needkeep)

  return needkeep

    

def removeSubFolders(dir, day, keepfile):

  subdirs = os.listdir(dir)

  for subdir in subdirs:

    subdir = os.path.join(dir,subdir)

    if ( not os.path.isdir(subdir)):

      continue

    print("----------------------")

    if( (not isKeepByDay(subdir, day))and (not isKeepByKeepfile(subdir, keepfile))):

      print("remove subfolder: " + subdir)

      import shutil

      shutil.rmtree(subdir,True)

    

def FolderCleanUp():

  (day, keepfile, dir) = getOption()

  dir = preCheckDir(dir)

  if dir is None:

    return

  removeSubFolders(dir,day,keepfile)

  

if __name__=='__main__':

  FolderCleanUp()

对目录下保留最后的zip文件:

def KeepLastNumZips(num)

    def extractTime(f):

        return os.path.getctime(f)
    zipfiles = [os.path.join(zipdir, f)

                for f in os.listdir(zipdir)

                if os.path.splitext(f)[1] == ".zip"]

    if len(zipfiles) > num:

        zipfiles.sort(key=extractTime, reverse=True)

        for i in range(num, len(zipfiles)):

            os.remove(zipfiles[i])
Python 相关文章推荐
使用python Django做网页
Nov 04 Python
python使用beautifulsoup从爱奇艺网抓取视频播放
Jan 23 Python
python 创建弹出式菜单的实现代码
Jul 11 Python
Python3编码问题 Unicode utf-8 bytes互转方法
Oct 26 Python
python实现指定字符串补全空格、前面填充0的方法
Nov 16 Python
python字符串分割及字符串的一些常规方法
Jul 24 Python
Pytorch实现各种2d卷积示例
Dec 30 Python
Python3列表List入门知识附实例
Feb 09 Python
Jupyter notebook如何实现指定浏览器打开
May 13 Python
python简单利用字典破解zip文件口令
Sep 07 Python
python包的导入方式总结
Mar 02 Python
Elasticsearch 数据类型及管理
Apr 19 Python
Python判断操作系统类型代码分享
Nov 22 #Python
python logging类库使用例子
Nov 22 #Python
Python中模拟enum枚举类型的5种方法分享
Nov 22 #Python
Python读写Excel文件方法介绍
Nov 22 #Python
Python中的包和模块实例
Nov 22 #Python
Python动态加载模块的3种方法
Nov 22 #Python
收集的几个Python小技巧分享
Nov 22 #Python
You might like
用PHP函数解决SQL injection
2006/12/09 PHP
php curl 伪造IP来源的实例代码
2012/11/01 PHP
laravel5.5添加echarts实现画图功能的方法
2019/10/09 PHP
js过滤数组重复元素的方法
2010/09/05 Javascript
使用JQuery快速实现Tab的AJAX动态载入(实例讲解)
2013/12/11 Javascript
js清除input中type等于file的值域(示例代码)
2013/12/24 Javascript
js中window.open打开一个新的页面
2014/08/10 Javascript
Javascript节点关系实例分析
2015/05/15 Javascript
JavaScript实现获得所有兄弟节点的方法
2015/07/23 Javascript
基于MVC5和Bootstrap的jQuery TreeView树形控件(二)之数据支持json字符串、list集合
2016/08/11 Javascript
浅谈js内置对象Math的属性和方法(推荐)
2016/09/19 Javascript
jQuery实现一个简单的轮播图
2017/02/19 Javascript
js canvas实现擦除效果示例代码
2017/04/26 Javascript
Vue不能检测到Object/Array更新的情况的解决
2018/06/26 Javascript
一文快速详解前端框架 Vue 最强大的功能
2019/05/21 Javascript
ES6数组与对象的解构赋值详解
2019/06/14 Javascript
layUI的验证码功能及校验实例
2019/10/25 Javascript
Vue生命周期activated之返回上一页不重新请求数据操作
2020/07/26 Javascript
Vue中使用Echarts仪表盘展示实时数据的实现
2020/11/01 Javascript
jquery自定义组件实例详解
2020/12/31 jQuery
[50:58]2018DOTA2亚洲邀请赛 4.1 小组赛 B组 Mineski vs EG
2018/04/03 DOTA
Python 中 -m 的典型用法、原理解析与发展演变
2019/11/11 Python
Python压缩模块zipfile实现原理及用法解析
2020/08/14 Python
详解利用python识别图片中的条码(pyzbar)及条码图片矫正和增强
2020/11/17 Python
localStorage的过期时间设置的方法详解
2018/11/26 HTML / CSS
魅力惠奢品线上平台:MEI.COM
2016/11/29 全球购物
阿联酋航空丹麦官方网站:Emirates DK
2019/08/25 全球购物
幼儿园秋游活动方案
2014/01/21 职场文书
卫校毕业生自我鉴定
2014/09/28 职场文书
校运会新闻稿
2015/07/17 职场文书
2015年数学教研工作总结
2015/07/22 职场文书
幼儿园小班教育随笔
2015/08/14 职场文书
如何撰写创业策划书
2019/06/27 职场文书
详解overflow:hidden的作用(溢出隐藏、清除浮动、解决外边距塌陷)
2021/07/01 HTML / CSS
python之基数排序的实现
2021/07/26 Python
Python+Selenium实现读取网易邮箱验证码
2022/03/13 Python