python实现的文件夹清理程序分享

 更新时间:2014年11月22日 15:30:25   投稿:junjie  
这篇文章主要介绍了python实现的文件夹清理程序分享,可以按时间清理和指定配置文件清理,需要的朋友可以参考下

使用:

复制代码 代码如下:

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

相关文章

  • OpenCV MediaPipe实现颜值打分功能

    OpenCV MediaPipe实现颜值打分功能

    这篇文章主要介绍了通过OpenCV MediaPipe实现摄像头实时检测颜值打分功能,文中的示例代码讲解详细,对我们学习Python有一定的帮助,感兴趣的可以了解一下
    2021-12-12
  • Python编程深度学习绘图库之matplotlib

    Python编程深度学习绘图库之matplotlib

    今天小编就为大家分享一篇关于Python编程深度学习绘图库之matplotlib,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12
  • Python实现给PDF添加水印的方法

    Python实现给PDF添加水印的方法

    这篇文章主要介绍了Python实现给PDF添加水印的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • go和python变量赋值遇到的一个问题

    go和python变量赋值遇到的一个问题

    这篇文章主要介绍了go和python变量赋值遇到的一个问题的相关资料,需要的朋友可以参考下
    2017-08-08
  • Python之循环结构

    Python之循环结构

    今天小编就为大家分享一篇关于Python之循环结构,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • pandas中DataFrame重置索引的几种方法

    pandas中DataFrame重置索引的几种方法

    在pandas中,经常对数据进行处理 而导致数据索引顺序混乱,从而影响数据读取、插入等,所以小编总结了几种索引重置的方法,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • Django Paginator分页器的使用示例

    Django Paginator分页器的使用示例

    django内置的分页器组件,能够帮我们实现对查询的数据进行自动分页,并返回分页对象,本文讲解分页器的用法
    2021-06-06
  • python教程之用py2exe将PY文件转成EXE文件

    python教程之用py2exe将PY文件转成EXE文件

    py2exe是一个将python脚本转换成windows上的可独立执行的可执行程序(*.exe)的工具,这样,你就可以不用装python而在windows系统上运行这个可执行程序。
    2014-06-06
  • Python中的 if 语句及使用方法

    Python中的 if 语句及使用方法

    这篇文章主要介绍了Python中的 if 语句及使用方法,包括条件测试、if -else 语句、if -elif-else 语句以及使用 if 语句处理列表操作,下面内容详细介绍组要的小伙伴可以参考一下
    2022-03-03
  • Python进行特征提取的示例代码

    Python进行特征提取的示例代码

    这篇文章主要介绍了Python进行特征提取的示例代码,帮助大家更好的进行数据分析,感兴趣的朋友可以了解下
    2020-10-10

最新评论