os、time模块按照时间创建和删除多级文件夹
按照时间创建多级文件夹
需求:
有时候日志或者其他文件需要放在创建时的时间节点的文件夹中,比如这个日志是在2020-11-12这个时间创建的,那就需要放在/2020/11/12这个多级的目录下面。
在很多时候都会用到
下面展示 按照当前时间创建文件夹的代码片
。
import os
import time
def file_storage(file_path):
tm = time.localtime(time.time())
# 获取系统当前年,月,日,小时
year = time.strftime('%Y', tm)
month = time.strftime('%m', tm)
day = time.strftime('%d', tm)
hour = time.strftime('%H', tm)
# 获取时分秒
hms = time.strftime("%H%M%S", tm)
# 根据当前日期创建图片文件
file_year = file_path + '/' + year
file_month = file_year + '/' + month
file_day = file_month + '/' + day
file_hour = file_day + '/' + hour
# 判断路径是否存在,没有则创建
if not os.path.exists(file_path):
os.makedirs(file_path)
os.mkdir(file_year)
os.mkdir(file_month)
os.mkdir(file_day)
os.mkdir(file_hour)
else:
if not os.path.exists(file_year):
os.mkdir(file_year)
os.mkdir(file_month)
os.mkdir(file_day)
os.mkdir(file_hour)
else:
if not os.path.exists(file_month):
os.mkdir(file_month)
os.mkdir(file_day)
os.mkdir(file_hour)
else:
if not os.path.exists(file_day):
os.mkdir(file_day)
os.mkdir(file_hour)
else:
if not os.path.exists(file_hour):
os.mkdir(file_hour)
return file_hour
path=r'C:\Users\xxx\Desktop\video_'
a=file_storage(path)
print(a)
可以看到 多级目录已经按照要求创建出来了.
按照时间删除多级目录下的文件
还有一些日常遇到的场景就是,保留最近30天的日志,
这个时候需要按照当前日期和保存n天来计算需要删除的文件夹,例如现在是2020-11-12 要保存最近12天的日志,那么2020-11-10之前的日志要全部删除。
下面直接上
代码
。
# 删除历史文件(保存n天)
def remove_files(del_path, n=30):
try:
excel_path = del_path + '/'
print("删除[{}]目录下{}天前的历史数据.".format(excel_path, n))
before_day = get_before_day(n)
year = before_day.split("-")[0]
month = before_day.split("-")[1]
day = before_day.split("-")[2]
if not os.path.exists(excel_path):
return
for fl in os.listdir(excel_path):
# 年份
if os.path.isdir(excel_path + fl) is False:
continue
if fl < year:
# 整个年份目录删除
shutil.rmtree(excel_path + fl, True)
elif fl == year:
for ff in os.listdir(excel_path + fl):
# 月份
if os.path.isdir(excel_path + fl + '/' + ff) is False:
continue
if ff < month:
# 整个月份目录删除
shutil.rmtree(excel_path + fl + '/' + ff, True)
elif ff == month:
# 判断日期
for dd in os.listdir(excel_path + fl + '/' + ff):
if dd <= day:
# 删除日期目录
shutil.rmtree(excel_path + fl + '/' + ff + '/' + dd, True)
else:
pass
else:
pass
except Exception as ex:
print("删除[{}]上级Files目录下[{}]天前的历史文件出错啦:{}".format(del_path, n, repr(ex)))
以上就是按照时间创建多级文件夹和按照时间删除多级文件的方案。
有需要的小伙伴可以借鉴下,see you!