【python实用小工具】每天自动创建文件归档目录
首先要利用到windows一个内置的程序, 完成定时任务 叫做任务计划程序
# =====================================
# 每天自动创建新目录, 删除空目录和过期目录
# =====================================
import os
import datetime
import logging
import shutil
import stat
today = datetime.date.today()
PATH = r"D:\archive" # 归档目录
period = 60 # 过期时间 天数
def set_logging():
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s %(filename)s : %(levelname)s %(message)s')
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
def create_today_dir():
path_today = os.path.join(PATH, str(today))
if not os.path.exists(path_today):
os.makedirs(path_today)
logging.warning("创建目录 %s" % path_today)
def delete_dir():
for dir_name in os.listdir(PATH):
try:
datetime.datetime.strptime(dir_name, "%Y-%m-%d") # 非日期名字的文件夹不做处理
except ValueError:
continue
dir_path = os.path.join(PATH, dir_name)
if os.path.isdir(dir_path):
if not os.listdir(dir_path): # 删除空目录
os.rmdir(dir_path)
logging.warning("删除目录 %s" % dir_path)
continue
if dir_name <= str(today - datetime.timedelta(period)): # 删除过期目录
def readonly_handler(func, path, info):
os.chmod(path, stat.S_IWRITE)
func(path)
shutil.rmtree(dir_path, onerror=readonly_handler) # 解决删除文件权限问题
logging.warning("删除目录 %s" % dir_path)
continue
if __name__ == "__main__":
set_logging()
delete_dir()
create_today_dir()