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 MySQLdb模块连接操作mysql数据库实例
Apr 08 Python
Python文件读取的3种方法及路径转义
Jun 21 Python
python 基础教程之Map使用方法
Jan 17 Python
scrapy爬虫完整实例
Jan 25 Python
python爬虫实例详解
Jun 19 Python
Python Numpy库datetime类型的处理详解
Jul 13 Python
python global关键字的用法详解
Sep 05 Python
python 和c++实现旋转矩阵到欧拉角的变换方式
Dec 04 Python
TensorFlow学习之分布式的TensorFlow运行环境
Feb 05 Python
解决python 找不到module的问题
Feb 12 Python
Python利用PyPDF2库获取PDF文件总页码实例
Apr 03 Python
python datetime处理时间小结
Apr 16 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
1.PHP简介
2006/10/09 PHP
逐步提升php框架的性能
2008/01/10 PHP
php 将bmp图片转为jpg等其他任意格式的图片
2009/06/21 PHP
深入extjs与php参数交互的详解
2013/06/25 PHP
PHP错误Cannot use object of type stdClass as array in错误的解决办法
2014/06/12 PHP
PHP弹出对话框技巧详细解读
2015/09/26 PHP
PHP使用栈解决约瑟夫环问题算法示例
2017/08/27 PHP
PHP中数组转换为SimpleXML教程
2019/01/27 PHP
PHP中str_split()函数的用法讲解
2019/04/11 PHP
JavaScript高级程序设计 阅读笔记(十三) js定义类或对象
2012/08/14 Javascript
FF火狐下获取一个元素同类型的相邻元素实现代码
2012/12/15 Javascript
jQuery对Select的操作大集合(收藏)
2013/12/28 Javascript
jquery 删除字符串最后一个字符的方法解析
2014/02/11 Javascript
jquery默认校验规则整理
2014/03/24 Javascript
JS实现漂亮的淡蓝色滑动门效果代码
2015/09/23 Javascript
JavaScript判断手机号运营商是移动、联通、电信还是其他(代码简单)
2015/09/25 Javascript
学习JavaScript设计模式(单例模式)
2015/11/26 Javascript
jQuery图片轮播插件——前端开发必看
2016/05/31 Javascript
从零学习node.js之搭建http服务器(二)
2017/02/21 Javascript
微信小程序 rich-text的使用方法
2017/08/04 Javascript
利用nginx + node在阿里云部署https的步骤详解
2017/12/19 Javascript
JS实现键值对遍历json数组功能示例
2018/05/30 Javascript
vue路由跳转传递参数的方式总结
2020/05/10 Javascript
TypeScript 运行时类型检查补充工具
2020/09/28 Javascript
HTML元素拖拽功能实现的完整实例
2020/12/04 Javascript
[50:15]VP vs Mineski 2018国际邀请赛淘汰赛BO3 第二场 8.22
2018/08/23 DOTA
Mac OS X10.9安装的Python2.7升级Python3.3步骤详解
2013/12/04 Python
python设置检查点简单实现代码
2014/07/01 Python
基于python实现百度翻译功能
2019/05/09 Python
个人自我评价和职业目标
2014/01/24 职场文书
借款协议书
2014/04/12 职场文书
2014年党风建设工作总结
2014/11/19 职场文书
中秋客户感谢信
2015/01/22 职场文书
公司开业主持词
2015/07/02 职场文书
Django模型层实现多表关系创建和多表操作
2021/07/21 Python
CSS Transition通过改变Height实现展开收起元素
2021/08/07 HTML / CSS