备份文件,从 D盘 到Z盘。并且保留15天的文件
import os import shutil from datetime import datetime, timedelta def move_and_clean_folders(a_folder, b_folder, keep_count=15): try: # 获取前两天的日期 yesterday = datetime.now() - timedelta(days=2) yesterday_str = yesterday.strftime('%Y-%m-%d') # 构建昨天的文件夹路径 source_folder = os.path.join(a_folder, yesterday_str) # 检查昨天的文件夹是否存在 if not os.path.exists(source_folder): print("Yesterday's folder does not exist.") return # 将昨天的文件夹剪切到 b 文件夹 destination_folder = os.path.join(b_folder, yesterday_str) shutil.move(source_folder, destination_folder) print(f"Moved folder {source_folder} to {destination_folder}") # 在 b 文件夹中保留最近的 keep_count 个文件夹,按文件名排序 folder_list = sorted([os.path.join(b_folder, d) for d in os.listdir(b_folder) if os.path.isdir(os.path.join(b_folder, d))], key=lambda x: os.path.basename(x)) # 删除除了最新的 keep_count 个文件夹之外的所有文件夹 for folder in folder_list[:-keep_count]: shutil.rmtree(folder) print(f"Deleted folder {folder}") except Exception as e: print(f"An error occurred: {e}") # 设置文件夹路径 a_folder = r"D:\自动备份\备份文件2" b_folder = r"z:\自动备份\备份文件2" # 调用函数 业务库 move_and_clean_folders(a_folder, b_folder, 15) # 设置文件夹路径 挖掘库 a_folder = r"D:\自动备份\备份文件1" b_folder = r"z:\自动备份\备份文件1" # 调用函数 move_and_clean_folders(a_folder, b_folder, 15)
标签:15,python,备份文件,文件夹,path,folder,os From: https://www.cnblogs.com/haoliansheng/p/18517329