• 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批量提交沙箱问题实例
  • 使用Python3 编写简单信用卡管理程序
  • python实现的二叉树算法和kmp算法实例
  • 详解Python编程中对Monkey Patch猴子补丁开发方式的运用
  • 简介二分查找算法与相关的Python实现示例
  • python 遍历字符串(含汉字)实例详解
  • 浅谈编码,解码,乱码的问题
  • Python SQLAlchemy基本操作和常用技巧(包含大量实例,非常好)
  • Python 检查数组元素是否存在类似PHP isset()方法
  • 基于进程内通讯的python聊天室实现方法

文章分类

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

最近更新的内容

    • Python常用正则表达式符号浅析
    • 总结用Pdb库调试Python的方式及常用的命令
    • python 实现网上商城,转账,存取款等功能的信用卡系统
    • Python中List.index()方法的使用教程
    • 在Python的gevent框架下执行异步的Solr查询的教程
    • python制作花瓣网美女图片爬虫
    • Python根据区号生成手机号码的方法
    • windows下wxPython开发环境安装与配置方法
    • Python读写txt文本文件的操作方法全解析
    • python学习笔记:字典的使用示例详解

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

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