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 相关文章推荐
详解Django中的ifequal和ifnotequal标签使用
Jul 16 Python
Python 3.x 连接数据库示例(pymysql 方式)
Jan 19 Python
Python实现采用进度条实时显示处理进度的方法
Dec 19 Python
Python 使用Numpy对矩阵进行转置的方法
Jan 28 Python
详解Python_shutil模块
Mar 15 Python
Python3多线程版TCP端口扫描器
Aug 31 Python
Python hashlib模块实例使用详解
Dec 24 Python
Matplotlib使用字符串代替变量绘制散点图的方法
Feb 17 Python
python 统计list中各个元素出现的次数的几种方法
Feb 20 Python
matplotlib阶梯图的实现(step())
Mar 02 Python
端午节将至,用Python爬取粽子数据并可视化,看看网友喜欢哪种粽子吧!
Jun 11 Python
Python加密与解密模块hashlib与hmac
Jun 05 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下保存远程图片到本地的办法
2010/08/08 PHP
php的日期处理函数及uchome的function_coomon中日期处理函数的研究
2011/01/12 PHP
PHP SEO优化之URL优化方法
2011/04/21 PHP
PHP批量生成静态HTML的简单原理和方法
2014/04/20 PHP
PHP网页游戏学习之Xnova(ogame)源码解读(三)
2014/06/23 PHP
php json中文编码为null的解决办法
2016/12/14 PHP
摘自启点的main.js
2008/04/20 Javascript
JavaScript 学习点滴记录
2009/04/24 Javascript
JS辨别访问浏览器判断是android还是ios系统
2014/08/19 Javascript
Jquery代码实现图片轮播效果(一)
2015/08/12 Javascript
在 Express 中使用模板引擎
2015/12/10 Javascript
jquery心形点赞关注效果的简单实现
2016/11/14 Javascript
基于vue2.0实现的级联选择器
2017/06/09 Javascript
关于Vue的路由权限管理的示例代码
2018/03/06 Javascript
JS逻辑运算符短路操作实例分析
2018/07/09 Javascript
在vue项目中引入高德地图及其UI组件的方法
2018/09/04 Javascript
VUE2.0+ElementUI2.0表格el-table实现表头扩展el-tooltip
2018/11/30 Javascript
vue elementUI 表单校验功能之数组多层嵌套
2019/06/04 Javascript
javascript自定义日期比较函数用法示例
2019/07/22 Javascript
vue props对象validator自定义函数实例
2019/11/13 Javascript
解决VUEX的mapState/...mapState等取值问题
2020/07/24 Javascript
Python程序设计入门(5)类的使用简介
2014/06/16 Python
Python开发如何在ubuntu 15.10 上配置vim
2016/01/25 Python
python3使用requests模块爬取页面内容的实战演练
2017/09/25 Python
Python的多维空数组赋值方法
2018/04/13 Python
浅谈python连续赋值可能引发的错误
2018/11/10 Python
Python使用grequests(gevent+requests)并发发送请求过程解析
2019/09/25 Python
Python通过yagmail实现发送邮件代码解析
2020/10/27 Python
HTML5语音识别标签写法附图
2013/11/18 HTML / CSS
德国骆驼商店:ActiveFashionWorld
2017/11/18 全球购物
药物学专业学生的自我评价
2013/10/27 职场文书
远程网络教育毕业生自我鉴定
2014/04/14 职场文书
乡镇精神文明建设汇报材料
2014/08/15 职场文书
秋季运动会演讲稿
2014/09/16 职场文书
总经理聘用协议书
2015/09/21 职场文书
解决vue $http的get和post请求跨域问题
2021/06/07 Vue.js