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的*args和**kwargs用法
Nov 01 Python
python使用新浪微博api上传图片到微博示例
Jan 10 Python
解决Python出现_warn_unsafe_extraction问题的方法
Mar 24 Python
python中文分词教程之前向最大正向匹配算法详解
Nov 02 Python
numpy中索引和切片详解
Dec 15 Python
python使用mysql的两种使用方式
Mar 07 Python
Python下调用Linux的Shell命令的方法
Jun 12 Python
将Python字符串生成PDF的实例代码详解
May 17 Python
深入了解如何基于Python读写Kafka
Dec 31 Python
keras的load_model实现加载含有参数的自定义模型
Jun 22 Python
什么是Python包的循环导入
Sep 08 Python
Python基于Tkinter开发一个爬取B站直播弹幕的工具
May 06 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中如何调用webservice的实例参考
2013/04/25 PHP
PHP如何将log信息写入服务器中的log文件
2015/07/29 PHP
JavaScript栏目列表隐藏/显示简单实现
2013/04/03 Javascript
JQuery中$(document)是什么意思有什么作用
2014/07/21 Javascript
js事件绑定快捷键以ctrl+k为例
2014/09/30 Javascript
JSON格式的键盘编码对照表
2015/01/29 Javascript
js实现刷新页面后回到记录时滚动条的位置【两种方案可选】
2016/12/12 Javascript
JavaScript利用闭包实现模块化
2017/01/13 Javascript
JS触摸与手势事件详解
2017/05/09 Javascript
ztree简介_动力节点Java学院整理
2017/07/19 Javascript
详解vue-cli项目中用json-sever搭建mock服务器
2017/11/02 Javascript
详解vue-cli脚手架build目录中的dev-server.js配置文件
2017/11/24 Javascript
浅谈让你的代码更简短,更整洁,更易读的ES6小技巧
2018/10/25 Javascript
vue+iview/elementUi实现城市多选
2019/03/28 Javascript
基于vue实现一个神奇的动态按钮效果
2019/05/15 Javascript
你不可不知的Vue.js列表渲染详解
2019/10/01 Javascript
react+antd 递归实现树状目录操作
2020/11/02 Javascript
跟老齐学Python之网站的结构
2014/10/24 Python
Python进度条实时显示处理进度的示例代码
2018/01/30 Python
浅谈Pycharm调用同级目录下的py脚本bug
2018/12/03 Python
Python中使用遍历在列表中添加字典遇到的坑
2019/02/27 Python
梅尔频率倒谱系数(mfcc)及Python实现
2019/06/18 Python
python3 assert 断言的使用详解 (区别于python2)
2019/11/27 Python
Python切片列表字符串如何实现切换
2020/08/06 Python
scrapy处理python爬虫调度详解
2020/11/23 Python
Python环境搭建过程从安装到Hello World
2021/02/05 Python
纯css3实现效果超级炫的checkbox复选框和radio单选框
2014/09/01 HTML / CSS
浅谈利用缓存来优化HTML5 Canvas程序的性能
2015/05/12 HTML / CSS
Canvas 帧动画吃苹果小游戏
2020/08/05 HTML / CSS
医院护理人员的自我评价分享
2013/10/04 职场文书
医学求职信
2014/05/28 职场文书
四年级学生期末评语
2014/12/26 职场文书
2015年党建工作总结
2015/03/30 职场文书
使用canvas实现雪花飘动效果的示例代码
2021/03/30 HTML / CSS
教你怎么用Python处理excel实现自动化办公
2021/04/30 Python
VW、VH适配移动端的解决方案与常见问题
2023/05/21 HTML / CSS