删除文件夹并且保留三天的文件夹
# -- coding: utf-8 --
import os
import datetime
import shutil
from apscheduler.schedulers.blocking import BlockingScheduler
# 删除文件夹
def del_file(filepath):
del_list = os.listdir(filepath)
for f in del_list:
file_path = os.path.join(filepath, f)
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
os.rmdir(filepath)
def run_task():
# 获得当天的日期
currentData = datetime.date.today()
# 获得图片所存的文件夹的路径
filePath = r"D:\capture"
file = os.listdir(filePath)
for str_data in file:
if str_data.startswith("20"):
fileData = datetime.date(*map(int, str_data.split("-")))
period_time = currentData - fileData
if currentData - fileData > datetime.timedelta(2):
# 五乱的图片保存路径
save_path = "D:/capture_fivechaos/" + str(fileData) + "/"
if not os.path.exists(save_path):
os.makedirs(save_path)
img_all_path = os.path.join(filePath, str_data)
img_all = os.listdir(img_all_path)
for img in img_all:
img_path = os.path.join(img_all_path, img)
if img.startswith("410115"):
# 保存五乱的图片
shutil.copy(img_path, os.path.join(save_path, img))
print("%s移除并创建成功".format(save_path))
# 保留三天的文件夹里的图片
del_file(os.path.join(filePath, str_data))
print("%s文件夹删除成功".format(os.path.join(filePath, str_data)))
print("定时任务结束")
if __name__ == '__main__':
print("定时任务启动")
sched = BlockingScheduler()
sched.add_job(run_task, 'cron', day_of_week='*', hour='11', minute='39', second='0')
sched.start()
bat篇
在电脑桌面上新建一个名为
del_file.bat
的批处理脚本
# 激活相应的conda环境
call activate pytorch_gpu
# 找到python的可执行程序
set python_path=D:\Programs_con\conda3\envs\pytorch_gpu\python.exe
# 设置运行的脚本文件的绝对路径
%python_path% D:\Project\del_file\keep_folder_for_three_days.py
pause
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiYTMfhHLlN3XnxCM38FdsYkRGZkRG9lcvx2bjxCMy8VZ6l2csA1UvVDcTFWNn90b1QULiVTQClGVF5UMR9Fd4VGdsATNfd3bkFGazxycykFaKdkYzZUbapXNXlleSdVY2pESa9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL4MWNwYmNhNGZlNDOjFGZ5cTY4QTZzYDO2U2Y2UzYiR2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
注意:
这篇博客是在python中实现定时任务,用bat来执行该脚本