Python定期删除文件、整理文件夹
1、根据传入的参数,文件所在目录,匹配文件的正则表达式,过期天数进行删除,这些可写在配置文件del_file.conf。
del_file3.py
#!/usr/bin/env python
# encoding: GBK
import os
import re
import sys
import time
import datetime
import logging
import shutil #reload(sys)
#sys.setdefaultencoding('utf-8') logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)-1d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',
filemode='a')
# logging.debug('This is debug message')
# logging.info('This is info message')
# logging.warning('This is warning message') def find_file(file_dir, file_re='\d{4}-\d{2}-\d{2}', expire_time=7):
# print sys.getdefaultencoding()
if file_re == '':
logging.error('file_re is null,exit')
return None
#解决编码问题
#file_dir = file_dir.decode("utf-8")
#file_re = file_re.decode("utf-8")
logging.info('传入参数 :目录 [%s],正则表达式[%s],过期天数 [%s]' % (file_dir,file_re,expire_time))
#目录下所有文件
all_file = os.listdir(file_dir)
#匹配正则的文件
reg_file_list = []
reg_str = file_re
for reg_file in all_file:
if re.match(reg_str,reg_file):
logging.info('正则匹配到文件:[%s]' % reg_file)
reg_file_list.append(reg_file)
if len(reg_file_list) <= 7:
logging.info('匹配文件数小于7个,不进行删除操作!')
return None
#满足过期时间的文件
#当前时间
today = datetime.datetime.now()
#n天
n_days = datetime.timedelta(days=int(expire_time))
#n天前日期
n_days_agos = today - n_days
#n天前时间戳
n_days_agos_timestamps = time.mktime(n_days_agos.timetuple()) for date_file in reg_file_list:
abs_file = os.path.join(file_dir,date_file)
file_timestamp = os.path.getmtime(abs_file)
if float(file_timestamp) <= float(n_days_agos_timestamps):
logging.info('过期匹配到文件:[%s]' % abs_file)
#print "匹配到文件:" ,abs_file
#返回满足条件的文件
if os.path.isfile(abs_file):
os.remove(abs_file)
logging.info('删除文件:[%s]成功' % abs_file)
if os.path.isdir(abs_file):
shutil.rmtree(abs_file)
logging.info('删除目录:[%s]成功' % abs_file) def read_conf(file_path):
with open(file_path,'r') as f:
for line in f:
line_list = line.strip().split(',')
if len(line_list) != 3:
logging.warning('%s 行配置不正确' % line.strip())
continue
file_dir = line_list[0]
file_re= line_list[1]
expire_time = line_list[2]
find_file(file_dir,file_re,expire_time) if __name__ == "__main__":
read_conf(sys.argv[1])
del_file.conf
C:\Users\Administrator\Desktop\Python学习\Python测试目录,.*数据,30
2 、定期整理日期文件或文件夹,传入参数:文件夹所在目录,匹配文件夹的正则表达式,整理多少天的文件夹,参数可写在配置文件dir_reg.conf。
move_file.py
#!/usr/bin/env python
# encoding: GBK
import os
import re
import sys
import time
import datetime
import logging
import shutil #reload(sys)
#sys.setdefaultencoding('utf-8') logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)-1d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='D:\\move.log',
filemode='a')
# logging.debug('This is debug message')
# logging.info('This is info message')
# logging.warning('This is warning message') def find_file(file_dir, file_re='数据', expire_time=60):
logging.info('传入参数 :目录 [%s],正则表达式[%s],过期天数 [%s]' % (file_dir,file_re,expire_time))
if not os.path.exists(file_dir):
logging.info('传入参数 :目录 [%s]不存在' % file_dir)
return None #匹配文件或目录 #目录下所有文件
all_file = os.listdir(file_dir)
#匹配正则的文件或目录
reg_file_list = []
reg_str = file_re
for reg_file in all_file:
#if os.path.isdir(reg_file):
# continue
if re.match(reg_str,reg_file):
logging.info('正则匹配到文件:[%s]' % reg_file)
reg_file_list.append(reg_file)
if len(reg_file_list) < 7:
logging.info('匹配文件数小于7个,不进行移动操作!')
return None
#满足过期时间的文件 #当前时间
today = datetime.datetime.now() #1天前时间
one_days = datetime.timedelta(days=1)
one_days_agos = today - one_days
#1天前时间文件夹
one_days_agos_dir = one_days_agos.strftime("%Y-%m-%d")
#1天前时间戳
one_days_agos_timestamps = time.mktime(one_days_agos.timetuple()) #n天前时间
n_days = datetime.timedelta(days=int(expire_time))
n_days_agos = today - n_days
#n天前时间文件夹
n_days_dir = n_days_agos.strftime("%Y-%m-%d")
#n天前时间戳
n_days_agos_timestamps = time.mktime(n_days_agos.timetuple()) #新建目录000-00-00~0000-00-00
date_dir = '%s_%s' %(n_days_dir,one_days_agos_dir)
if not os.path.exists(os.path.join(file_dir,date_dir)):
os.mkdir(os.path.join(file_dir,date_dir)) #移动1~n天期间的文件或目录
for date_file in reg_file_list:
abs_file = os.path.join(file_dir,date_file)
file_timestamp = os.path.getctime(abs_file)
if float(n_days_agos_timestamps) <= float(file_timestamp) <= float(one_days_agos_timestamps):
logging.info('移动文件:[%s]' % abs_file)
#print "匹配到文件:" ,abs_file
#移动满足条件的文件
shutil.move(abs_file, os.path.join(file_dir,date_dir))
logging.info('移动:[%s]到[%s]成功' % (abs_file,os.path.join(file_dir,date_dir))) def read_conf(file_path):
with open(file_path,'r') as f:
for line in f:
line_list = line.strip().split(',')
if len(line_list) != 3:
logging.warning('%s 行配置不正确' % line.strip())
continue
file_dir = line_list[0]
file_re= line_list[1]
expire_time = line_list[2]
find_file(file_dir,file_re,expire_time) if __name__ == "__main__":
read_conf(sys.argv[1])
dir_reg.conf
D:\mylog,^\d{4}-\d{2}-\d{2}$,30
D:\mylog,^\d{4}-\d{2}-\d{2}$,90
Python定期删除文件、整理文件夹的更多相关文章
- 定期删除IIS日志文件
服务器中由于监控的需要会经常生成很多日志文件,比如IIS日志文件(C:\inetpub\logs\LogFiles),一个稍微有流量的网站,其日志每天可以达到上百兆,这些文件日积月累会严重的占用服务器 ...
- Linux创建一个周期任务来定期删除过期的文件
一:需求 在开发中存在这样的情况,为了防止文件的误删,不允许开发人员直接删除项目中要用到的文件,而是将它们移动到某个目录,然后由一个周期任务去检测并删除内部过期的文件: 二:检测文件是否是过期文件 有 ...
- shell定期转移日志文件到云盘并定期删除云盘文件
shell 脚本定期处理如下: cat /home/backup/logs_delete.sh #!/bin/bash /bin/find /data/logs/nginx/ -name " ...
- python删除文件和文件夹
python中删除文件:os.remove(path) path为文件的路径 import os os.remove(path) python中删除文件夹:shutil.rmtree(path) pa ...
- 使用python删除一个文件或文件夹
使用python删除一个文件或文件夹,需要使用os模块. import osos.remove(path) # path是文件的路径,如果这个路径是一个文件夹,则会抛出OSError的错误,这时需用用 ...
- 【转】 python 删除非空文件夹
转自:https://blog.csdn.net/xiaodongxiexie/article/details/77155864 一般删除文件时使用os库,然后利用os.remove(path)即可完 ...
- Python学习笔记(20)-文件和文件夹的移动、复制、删除、重命名
一,概述 python中对文件和文件夹进行移动.复制.删除.重命名,主要依赖os模块和shutil模块,要死记硬背这两个模块的方法还是比较困难的,可以用一个例子集中演示文件的移动.复制.删除.重命名, ...
- Python 删除文件与文件夹
版权所有,未经许可,禁止转载 章节 Python 介绍 Python 开发环境搭建 Python 语法 Python 变量 Python 数值类型 Python 类型转换 Python 字符串(Str ...
- 如何使用python移除/删除非空文件夹?
移除/删除非空文件夹/目录的最有效方法是什么? 1.标准库参考:shutil.rmtree. 根据设计,rmtree在包含只读文件的文件夹树上失败.如果要删除文件夹,不管它是否包含只读文件,请使用 i ...
随机推荐
- BZOJ.1312.[Neerc2006]Hard Life(分数规划 最大权闭合子图)
BZOJ 最大密度子图. 二分答案\(x\),转为求是否存在方案满足:\(边数-x*点数\geq 0\). 选一条边就必须选两个点,所以可以转成最大权闭合子图.边有\(1\)的正权,点有\(x\)的负 ...
- 数学——Euler方法求解微分方程详解(python3)
算法的数学描述图解 实例 用Euler算法求解初值问题 \[ \frac{dy}{dx}=y+\frac{2x}{y^2}\] 初始条件\(y(0)=1\),自变量的取值范围\(x \in [0, 2 ...
- 基于CC2530/CC2430 的温度采集系统--DS18B20
DS18B20是常用的温度传感器.CC2530 采集DS18B20 可以实现温度采集系统等等. 模块链接:https://item.taobao.com/item.htm?id=54130861732 ...
- 潭州课堂25班:Ph201805201 tornado 项目 第一课 项目介绍和创建 (课堂笔记)
tornado 相关说明 , 查找 python3 的路径: binbin@abc:~$ which python3/usr/bin/python3 创建虚拟环境 : 创建工程; 用 pycharm ...
- BZOJ1515 : [POI2006]Lis-The Postman
首先,如果这个图本身就不存在欧拉回路,那么显然无解. 对于每个子串: 1.如果里面有不存在的边,那么显然无解. 2.如果里面有一条边重复出现,那么显然也无解. 3.对于每条边,维护其前驱与后继,若前驱 ...
- app的创建和注册
APP是用来存放代码的 创建APP 命令行创建,切换到项目目录下 python manage.py startapp appo1 #app01为项目名,创建完刷新即可 目录结构 把函数放到views后 ...
- Android Studio 设置字体
File->Settings->Editor->Colors & Fonts->Font->Editor Font
- 对学习Ajax的知识总结
1.对Ajax的初步认识 1.1. Ajax 是一种网页开发技术,(Asynchronous Javascript + XML)异步 JavaScript 和 XML: 1.2.Ajax 是异步交互, ...
- 了解CSS/CSS3原生变量var (转)
一.变量是个好东西 在任何语言中,变量的有一点作用都是一样的,那就是可以降低维护成本,附带还有更高性能,文件更高压缩率的好处. 随着CSS预编译工具Sass/Less/Stylus的关注和逐渐流行,C ...
- JAVA自学笔记03
1.三目运算符 1)格式:(关系表达式)?表达式1:表达式2 true则执行表达式1,false则执行表达式2 @ 例题1 :求两数中的较大值 System.out.println(x>y?x: ...