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)