python实现的文件夹清理程序分享
作者:junjie 发布时间:2021-07-20 07:58:57
使用:
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])
猜你喜欢
- sql xml 入门: --by jinjazz 1、xml: 能认识元素、属性和值 2、xpath: 寻址语言,类似windows目录的查
- 我就废话不多说了,大家还是直接看代码吧~//isSymbol表示有无符号func BytesToInt(b []byte, isSymbol
- 感觉很流畅的键盘控制(带惯性) <body> <div id="man" style="po
- 在进行matplotlib画图的时候,经常会出现这个的报错,虽然知道是因为没有对应的字体的原因,但是,将字体下载后放到目标路径下,仍然没有办
- RateLimit 限流中间件为什么需要限流中间件在大数据量高并发访问时,经常会出现服务或接口面对大量的请求而导致数据库崩溃的情况,甚至引发
- 教育信息化时代,考试成绩也要求上网公布。一次我将考试成绩制作成一个HTML文件,如图1所示,领导审查的意见是“将成绩按名次排列”,可是所有的
- 保存文件名太长OSError: [Errno 36] File name too lon问题描述安装pip install python-d
- 一、密码字典所谓密码字典,主要是配合解密使用,一般情况用来暴力破解密码,是由指定字符排列组合组成的文本文件。如果知道密码设置的规律指定性生成
- 匿名管道管道是一个单向通道,有点类似共享内存缓存.管道有两端,包括输入端和输出端.对于一个进程的而言,它只能看到管道一端,即要么是输入端要么
- 单例模式的概念单例模式很容易记住。就像名称一样,它只能提供对象的单一实例,保证一个类只有一个实例,并提供一个全局访问该实例的方法。在第一次调
- 1、cURL请求的基本步骤:(1)初始化(2)设置选项,包括URL(3)执行并获取HTML文档内容(4)释放cURL句柄<?php&n
- 前言这几天比较空闲,就接触了下百度地图的API(开发者中心链接地址:http://developer.baidu.com),发现调用还是挺方
- 暴力的重启服务方案一般服务器重启可以直接通过 kill 命令杀死进程,然后重新启动一个新的进程即可。但这种方法比较粗暴,有可能导致某些正在处
- 模块之turtle小故事前两天朋友说:“常文啊!听说你会python,那能不能用python画一些好看的图呢?”然后我特意去学了一下turt
- 本文实例讲述了JavaScript设计模式之享元模式。分享给大家供大家参考,具体如下:通过两个例子的对比来凸显享元模式的特点:享元模式是一个
- 查询游戏历史成绩最高分前100Sql代码SELECT ps.* FROM cdb_playsgame ps WHERE ps.credits
- 本文内容会引起杀毒软件的莫名兴奋,建议先安抚杀毒软件,让杀毒软件先休息一下再继续操作安装python3.6转exe会遇到很多问题,其中部分是
- Windows下将gvim8配置为Python IDE大概分为以下四步,每步介绍的都非常详细,一起看看吧。1.准备工作将下面的安装包或者文件
- 最近做一个车牌识别项目,入门级别的,十分简单。车牌识别总体分成两个大的步骤:一、车牌定位:从照片中圈出车牌二、车牌字符识别这里只说第二个步骤
- javascript函数的定义1:调用关键字function来构造,如:function distance(x1,x2,y1,y2){var