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

相关文章

  • Keras深度学习模型Sequential和Model详解

    Keras深度学习模型Sequential和Model详解

    这篇文章主要介绍了Keras深度学习模型Sequential和Model详解,在Keras中有两种深度学习的模型:序列模型(Sequential)和通用模型(Model),差异在于不同的拓扑结构,,需要的朋友可以参考下
    2023-08-08
  • python实现用类读取文件数据并计算矩形面积

    python实现用类读取文件数据并计算矩形面积

    今天小编就为大家分享一篇python实现用类读取文件数据并计算矩形面积,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • Python绘制移动均线方法 含源代码

    Python绘制移动均线方法 含源代码

    上一篇文章我们介绍了Python绘制专业的K线图,讲解了数据获取、K线图绘制及成交量绘制等内容。本篇将在上一篇的基础上,继续讲解移动均线的绘制,需要的朋友可以参考下
    2021-10-10
  • python绘制散点图详细步骤(从0到1必会)

    python绘制散点图详细步骤(从0到1必会)

    这篇文章主要介绍了如何使用Python绘制散点图,包括导入包、准备数据、绘制图像、修饰图像(添加标题、坐标轴标签、颜色图例)以及整合所有代码,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-12-12
  • python3中datetime库,time库以及pandas中的时间函数区别与详解

    python3中datetime库,time库以及pandas中的时间函数区别与详解

    这篇文章主要介绍了python3中datetime库,time库以及pandas中的时间函数区别与详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • 对python3.4 字符串转16进制的实例详解

    对python3.4 字符串转16进制的实例详解

    今天小编就为大家分享一篇对python3.4 字符串转16进制的实例详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-06-06
  • Win8.1下安装Python3.6提示0x80240017错误的解决方法

    Win8.1下安装Python3.6提示0x80240017错误的解决方法

    这篇文章主要为大家详细介绍了Win8.1下安装Python3.6提示0x80240017错误的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-07-07
  • python绘制已知点的坐标的直线实例

    python绘制已知点的坐标的直线实例

    今天小编就为大家分享一篇python绘制已知点的坐标的直线实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • python3.3使用tkinter开发猜数字游戏示例

    python3.3使用tkinter开发猜数字游戏示例

    这篇文章主要介绍了python3.3使用tkinter开发猜数字游戏示例,需要的朋友可以参考下
    2014-03-03
  • python面积图之曲线图的填充

    python面积图之曲线图的填充

    这篇文章主要介绍了python面积图之曲线图的填充,文章围绕主题的相关资料展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下,希望对你的学习有所帮助
    2022-06-06

最新评论