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框架中编写Contact表单的教程
Jul 17 Python
Python的条件语句与运算符优先级详解
Oct 13 Python
轻松掌握python设计模式之访问者模式
Nov 18 Python
用matplotlib画等高线图详解
Dec 14 Python
Django配置celery(非djcelery)执行异步任务和定时任务
Jul 16 Python
Python反射和内置方法重写操作详解
Aug 27 Python
解读python如何实现决策树算法
Oct 11 Python
Python面向对象之Web静态服务器
Sep 03 Python
三个python爬虫项目实例代码
Dec 28 Python
PyQt5事件处理之定时在控件上显示信息的代码
Mar 25 Python
Python爬虫破解登陆哔哩哔哩的方法
Nov 17 Python
python 基于Apscheduler实现定时任务
Dec 15 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在DOS命令行下却无法链接MySQL的技术笔记
2010/12/29 PHP
php 使用fopen函数创建、打开文件详解及实例代码
2016/09/24 PHP
PHP实现正则表达式分组捕获操作示例
2018/02/03 PHP
js DataSet数据源处理代码
2010/03/29 Javascript
js对象的构造和继承实现代码
2010/12/05 Javascript
js 验证密码强弱的小例子
2013/03/21 Javascript
jQuery表格的维护和删除操作
2017/02/03 Javascript
解决mpvue + vuex 开发微信小程序vuex辅助函数mapState、mapGetters不可用问题
2018/08/03 Javascript
JavaScript使用面向对象实现的拖拽功能详解
2019/06/12 Javascript
浅谈layer的Icon样式以及一些常用的layer窗口使用方法
2019/09/11 Javascript
js实现窗口全屏示例详解
2019/09/17 Javascript
vue-cli+iview项目打包上线之后图标不显示问题及解决方法
2019/10/16 Javascript
解决vue自定义全局消息框组件问题
2019/11/22 Javascript
[03:07]DOTA2英雄基础教程 冰霜诅咒极寒幽魂
2013/12/06 DOTA
Python文件操作类操作实例详解
2014/07/11 Python
python中的五种异常处理机制介绍
2014/09/02 Python
python实现RSA加密(解密)算法
2016/02/17 Python
Python3.6简单操作Mysql数据库
2017/09/12 Python
pandas object格式转float64格式的方法
2018/04/10 Python
详解Python中is和==的区别
2019/03/21 Python
用Python绘制漫步图实例讲解
2020/02/26 Python
django在开发中取消外键约束的实现
2020/05/20 Python
Mountain Hardwear官网:攀岩服装和户外装备
2019/09/26 全球购物
冰淇淋店创业计划书范文
2013/12/27 职场文书
怎么写自荐书范文
2014/02/12 职场文书
水毁工程实施方案
2014/04/01 职场文书
教师评语大全
2014/04/28 职场文书
学生检讨书怎么写?
2014/10/10 职场文书
实习生矿工检讨书
2014/10/13 职场文书
2014党的群众路线教育实践活动学习心得体会
2014/10/31 职场文书
2015年宣传工作总结
2015/04/08 职场文书
会议室管理制度范本
2015/08/06 职场文书
Go遍历struct,map,slice的实现
2021/06/13 Golang
【2·13】一图读懂中国无线电发展
2022/02/18 无线电
Oracle数据库事务的开启与结束详解
2022/06/25 Oracle
spring boot实现文件上传
2022/08/14 Java/Android