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实现查询苹果手机维修进度
Mar 16 Python
Python程序包的构建和发布过程示例详解
Jun 09 Python
对Python3之方法的覆盖与super函数详解
Jun 26 Python
对python中GUI,Label和Button的实例详解
Jun 27 Python
python 使用plt画图,去除图片四周的白边方法
Jul 09 Python
Python Django 命名空间模式的实现
Aug 09 Python
django 数据库连接模块解析及简单长连接改造方法
Aug 29 Python
python通过opencv实现图片裁剪原理解析
Jan 19 Python
Python模块future用法原理详解
Jan 20 Python
Python3 Click模块的使用方法详解
Feb 12 Python
Python+MySQL随机试卷及答案生成程序的示例代码
Feb 01 Python
Python  序列化反序列化和异常处理的问题小结
Dec 24 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
文件上传类
2006/10/09 PHP
php中处理mysql_fetch_assoc返回来的数组 不用foreach----echo
2011/05/04 PHP
PHP数组的交集array_intersect(),array_intersect_assoc(),array_inter_key()函数的小问题
2011/05/29 PHP
php的memcached客户端memcached
2011/06/14 PHP
ThinkPHP3.2.2的插件控制器功能简述
2014/07/09 PHP
php双层循环(九九乘法表)
2017/10/23 PHP
Laravel如何实现自动加载类
2019/10/14 PHP
PHP pthreads v3下同步处理synchronized用法示例
2020/02/21 PHP
jQuery live
2009/05/15 Javascript
Prototype 工具函数 学习
2009/07/23 Javascript
javascript日期对象格式化为字符串的实现方法
2014/01/14 Javascript
Angularjs 基础入门
2014/12/26 Javascript
javascript实现类似百度分享功能的方法
2015/07/27 Javascript
JavaScript入门基础
2015/08/12 Javascript
Bootstrap轮播插件简单使用方法介绍
2016/06/21 Javascript
详解微信小程序中的页面代码中的模板的封装
2017/10/12 Javascript
VUE2.0中Jsonp的使用方法
2018/05/22 Javascript
微信小程序实现上传多个文件 超过10个
2020/03/30 Javascript
小程序中的箭头函数的具体使用
2020/06/19 Javascript
vue实现移动端input上传视频、音频
2020/08/18 Javascript
swiperjs实现导航与tab页的联动
2020/12/13 Javascript
使用Python判断IP地址合法性的方法实例
2014/03/13 Python
Python中模块与包有相同名字的处理方法
2017/05/05 Python
python如何让类支持比较运算
2018/03/20 Python
Python读取视频的两种方法(imageio和cv2)
2018/04/15 Python
python 从csv读数据到mysql的实例
2018/06/21 Python
python获取本机所有IP地址的方法
2018/12/26 Python
python3.7添加dlib模块的方法
2020/07/01 Python
教你如何一步一步用Canvas写一个贪吃蛇
2018/10/22 HTML / CSS
泰国最新活动和优惠:Megatix
2020/05/07 全球购物
活动邀请函范文
2014/01/19 职场文书
群众路线表态发言材料
2014/10/17 职场文书
班主任经验交流材料
2014/12/16 职场文书
党支部先进事迹材料
2014/12/24 职场文书
2015年林业工作总结
2015/05/14 职场文书
SQL注入篇学习之盲注/宽字节注入
2022/03/03 MySQL