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 UnicodeEncodeError: 'gbk' codec can't encode character 解决方法
Apr 24 Python
在Django中限制已登录用户的访问的方法
Jul 23 Python
判断网页编码的方法python版
Aug 12 Python
Python针对给定列表中元素进行翻转操作的方法分析
Apr 27 Python
python中使用 xlwt 操作excel的常见方法与问题
Jan 13 Python
python解析xml简单示例
Jun 21 Python
解决python3插入mysql时内容带有引号的问题
Mar 02 Python
python3实现简单飞机大战
Nov 29 Python
解决python 执行shell命令无法获取返回值的问题
Dec 05 Python
Python基础教程,Python入门教程(超详细)
Jun 24 Python
Python编程super应用场景及示例解析
Oct 05 Python
python可视化分析绘制带趋势线的散点图和边缘直方图
Jun 25 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查询MySQL大量数据的时候内存占用分析
2011/07/22 PHP
mantis安装、配置和使用中的问题小结
2014/07/14 PHP
PHP实现自动登入google play下载app report的方法
2014/09/23 PHP
Javascript学习笔记5 类和对象
2010/01/11 Javascript
jquery提取元素里的纯文本不包含span等里的内容
2013/09/30 Javascript
关闭时刷新父窗口两种方法
2014/05/07 Javascript
Nodejs学习笔记之Stream模块
2015/01/13 NodeJs
[原创]jQuery常用的4种加载方式分析
2016/07/25 Javascript
使用DeviceOne实现微信小程序功能
2016/12/29 Javascript
Vue中计算属性computed的示例解读
2017/07/26 Javascript
vue左右侧联动滚动的实现代码
2018/06/06 Javascript
微信小程序自定义select下拉选项框组件的实现代码
2018/08/28 Javascript
记录微信小程序 height: calc(xx - xx);无效问题
2019/12/30 Javascript
JavaScript常用工具函数库汇总
2020/09/17 Javascript
Python实现远程调用MetaSploit的方法
2014/08/22 Python
Python中文件操作简明介绍
2015/04/13 Python
python从sqlite读取并显示数据的方法
2015/05/08 Python
Python的Django框架中从url中捕捉文本的方法
2015/07/20 Python
利用Python如何生成hash值示例详解
2017/12/20 Python
Python实现的多进程和多线程功能示例
2018/05/29 Python
在tensorflow中设置使用某一块GPU、多GPU、CPU的操作
2020/02/07 Python
Python基于Dlib的人脸识别系统的实现
2020/02/26 Python
Python selenium模块实现定位过程解析
2020/07/09 Python
LA MER海蓝之谜美国官网:传奇面霜
2016/08/27 全球购物
婚前协议书怎么写
2014/04/15 职场文书
电子商务专业自荐信
2014/06/02 职场文书
处级领导干部四风问题自我剖析材料
2014/09/29 职场文书
群众路线学习笔记范文
2014/11/06 职场文书
保送生自荐信范文
2015/03/26 职场文书
2015年宣传部工作总结范文
2015/03/31 职场文书
2015年健康教育工作总结
2015/04/10 职场文书
检察院起诉意见书
2015/05/20 职场文书
超强台风观后感
2015/06/09 职场文书
公司回复函格式
2015/07/14 职场文书
用Python将库打包发布到pypi
2021/04/13 Python
ORACLE中dbms_output.put_line输出问题的解决过程
2022/06/28 Oracle