• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > python实现的文件夹清理程序分享

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

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python 创建文件夹,python 遍历文件夹,python如何创建文件夹,python 删除文件夹,python读取文件夹等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

使用:
foldercleanup.py -d 10 -k c:\test\keepfile.txt c:\test
</div>
表示对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()
</div>

对目录下保留最后的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])
</div>

</div>

您可能想查找下面的文章:

  • Python遍历文件夹和读写文件的实现方法
  • Python实现Windows和Linux之间互相传输文件(文件夹)的方法
  • python 实现删除文件或文件夹实例详解
  • Python文件与文件夹常见基本操作总结
  • python之文件的读写和文件目录以及文件夹的操作实现代码
  • Python遍历文件夹和读写文件的实现代码
  • 动感网页相册 python编写简单文件夹内图片浏览工具
  • python之文件的读写和文件目录以及文件夹的操作实现代码
  • Python遍历文件夹和读写文件的实现代码
  • 动感网页相册 python编写简单文件夹内图片浏览工具

相关文章

  • python里对list中的整数求平均并排序
  • 常见的在Python中实现单例模式的三种方法
  • Python程序中设置HTTP代理
  • Python爬取qq music中的音乐url及批量下载
  • Python编程中的文件操作攻略
  • python实现sublime3的less编译插件示例
  • Pycharm学习教程(1) 定制外观
  • 基于Python的身份证号码自动生成程序
  • python模拟登录百度贴吧(百度贴吧登录)实例
  • python多线程编程方式分析示例详解

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • 在Python中操作字符串之replace()方法的使用
    • Python中asyncore异步模块的用法及实现httpclient的实例
    • Python 如何访问外围作用域中的变量
    • Python验证码识别处理实例
    • Python多线程经典问题之乘客做公交车算法实例
    • python 打印对象的所有属性值的方法
    • Python的Urllib库的基本使用教程
    • python executemany的使用及注意事项
    • Python计算字符宽度的方法
    • py中的目录与文件判别代码

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有