使用:

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])

完!

转载于:https://www.cnblogs.com/itech/archive/2011/01/11/1915718.html

python实例31[文件夹清理]相关推荐

  1. Python实例--遍历文件夹下所有的文件或文件夹

    一.前言 最近在跑深度学习的网络模型,跑通代码的前提是要读取数据集,众所周知,深度学习的数据集是非常庞大的,动辄就几个G,想要一个一个的输入无疑是天方夜谭,因此,利用Python遍历数据集就显得非常重 ...

  2. Python实例 遍历文件夹和文件

    import  os import  os.path #  os,os.path里包含大多数文件访问的函数,所以要先引入它们. #  请按照你的实际情况修改这个路径 rootdir  =   &quo ...

  3. python删除指定文件夹下文件和文件夹的方法

    python删除指定文件夹下的文件,是一个常用的功能.我找了不少地方,一直没有找到合适的模版,那只好自己倒腾一个比较实用的模版了. 基本模块 这里面会用到几个模块,一个是目录下所有文件的的函数:lis ...

  4. Python监控目录文件夹,并使用SFTP上传目录及文件到linux服务器

    Python 扫描监控本地文件夹并进行超大文件上传 方案1:WebUploader大文件分块多线程并发上传 方案2:watchdog目录文件夹监控,paramiko STFP上传服务器 方案3:优化2 ...

  5. python读取一个文件夹/子文件夹下的所有文件名字

    python读取一个文件夹/子文件夹下的所有文件名字 示例代码: import osfile_path = './images/' all_file_name = os.listdir(file_pa ...

  6. Python递归获取文件夹下面所有文件名字:

    Python递归获取文件夹下面所有文件名字: def getAllFiles(targetDir):files = []listFiles = os.listdir(targetDir)for i i ...

  7. python 打开当前目录的txt文件-Python - 读取其他文件夹/目录中的文本文件

    这是我的情况:我有一些.txt文件在我可以运行脚本的不同目录中.Python - 读取其他文件夹/目录中的文本文件 mainDir/ -face/ -57268-face-_tracker.txt - ...

  8. python下载文件到指定目录-Python获取指定文件夹下的文件名的方法

    本文采用os.walk()和os.listdir()两种方法,获取指定文件夹下的文件名. 一.os.walk() 模块os中的walk()函数可以遍历文件夹下所有的文件. os.walk(top, t ...

  9. python怎么读文件夹下的文件夹-python如何获取当前文件夹下所有文件名详解

    前言 本文主要给大家介绍了关于python获取当前文件夹下所有文件名的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧 os 模块下有两个函数: os.walk() os.li ...

最新文章

  1. 数据结构与算法笔记 - 绪论
  2. c程序设计语言第五单元,(C语言程序设计基础课件)第五单元循环结构程序设计.pptx...
  3. PHP----------线程安全和非线程安全的介绍
  4. 洛谷P6302:回家路线(斜率优化)
  5. 基于android平台的24点游戏设计与实现需求分析,基于Android平台的24点游戏设计与实现需求分析_毕业设计论文.doc...
  6. Qt编写的线损分析工具
  7. Ionic常见问题--插件无法下载:npm ERR打包sha1错误
  8. HeitiCSEG 文鼎CS大黑 字体下载
  9. Linux性能测试(UnixBench)(bench)一键脚本
  10. 基于Hive解析AST的模仿sqlFlow无中间表的字段级数据血缘的后端
  11. html中怎样做成相册的效果,CSS相册简单实现方法(功能分析及代码)
  12. python安装失败未指定_win7 64 位安装 python,提示: 0x80240017-未指定的错误
  13. MCU芯片设计和软件开发
  14. UG二次开发 获取零件的中心
  15. 怎么转换CAD文件的版本?分享两种转换版本的方法
  16. 摘自《机器视觉技术》陈兵旗—机器视觉的功能与精度
  17. Alpha 事后诸葛亮
  18. c++:利用socket基于TPC/IP实现通信 在线聊天
  19. B站品牌营销!寻找优质UP主内容共创
  20. 1 W 字 | 硬刚 MySQL

热门文章

  1. python批量打印机excel,python自动化办公系列03_单个以及批量处理excel文件
  2. python解图片迷宫生成路径_用Python代码来解图片迷宫的方法整理
  3. 计算机技术员好学吗,电脑技术员,沦落到如此地步...
  4. android 足球游戏,足球游戏哪个好玩,安卓单机足球游戏哪个好玩
  5. Linux下开启mysql数据库的远程访问权限
  6. Android入门(13)| Android权限 与 内容提供器
  7. leetcode614. 二级关注者(SQL)
  8. (八)nodejs循序渐进-事件驱动(进阶篇)
  9. 深度学习(06)-- Network in Network(NIN)
  10. 《深入理解JVM.2nd》笔记(三):垃圾收集器与垃圾回收策略