```python import os import time from tqdm import tqdm # 取得來源資料夾路徑並去除引號與斜線 folder_path = input("請輸入來源資料夾的路徑:").strip().strip('"').rstrip(os.sep) # 判斷資料夾名稱或磁碟機代號 if os.path.splitdrive(folder_path)[1] == '': folder_name = os.path.splitdrive(folder_path)[0].replace(':', '') else: folder_name = os.path.basename(folder_path) # 設定時間戳記 timestamp = time.strftime("%Y%m%d%H%M%S") today_date = time.strftime("%Y-%m-%d %A") # 生成文件建立日期 # 設定儲存檔案的路徑(桌面) desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") file_path = os.path.join(desktop_path, f"{folder_name}_{timestamp}.md") error_log_path = os.path.join(desktop_path, f"{folder_name}_{timestamp}_errorlog.txt") # 開啟錯誤日誌檔案 error_log = open(error_log_path, 'w', encoding='utf-8') # 計算資料夾內的資料夾和檔案數量,並計算檔案總容量 def count_items(folder): num_folders = 0 num_files = 0 total_size = 0 try: for item in os.listdir(folder): if item == '@Recycle': # 跳過 @Recycle 資料夾 continue item_path = os.path.join(folder, item) if os.path.isdir(item_path): num_folders += 1 else: try: total_size += os.path.getsize(item_path) # 加入檔案大小計算 num_files += 1 except FileNotFoundError: error_log.write(f"檔案未找到: {item_path}\n") except PermissionError: error_log.write(f"無法存取檔案: {item_path}\n") except PermissionError: error_log.write(f"存取被拒: {folder}\n") return num_folders, num_files, total_size # 將檔案容量格式化為 KB 或 MB def format_size(size): for unit in ['B', 'KB', 'MB', 'GB', 'TB']: if size < 1024: return f"{size:.2f} {unit}" size /= 1024 return f"{size:.2f} TB" # 遍歷資料夾,生成 Markdown 格式的列表,並加入 tqdm 進度條 def generate_markdown(folder, level=1, is_first_layer=False): markdown = "" indent = " " * level try: num_folders, num_files, total_size = count_items(folder) folder_name = os.path.basename(folder.strip(os.sep)) size_str = format_size(total_size) # 格式化檔案容量 # 略過第一層資料夾名稱(只在第一次顯示) if not is_first_layer: markdown += f"{indent}- {folder_name} (內含{num_folders}個資料夾,{num_files}個檔案,本層檔案容量 {size_str})\n" items = os.listdir(folder) for item in tqdm(items, desc=f"處理資料夾: {folder_name}", unit="項"): if item == '@Recycle': # 跳過 @Recycle 資料夾 continue item_path = os.path.join(folder, item) if os.path.isdir(item_path): markdown += generate_markdown(item_path, level + 1) except PermissionError: error_log.write(f"存取被拒: {folder}\n") return markdown # 生成 Markdown 內容 markdown_header = f"---\ncreated:: [[{today_date}]]\n---\n\n# MD資料夾結構 : {folder_name}\n\n" # 在第一層資料夾只顯示一次來源資料夾名稱 num_folders, num_files, total_size = count_items(folder_path) size_str = format_size(total_size) markdown_content = f"- {folder_name} (內含{num_folders}個資料夾,{num_files}個檔案,本層檔案容量 {size_str})\n" + generate_markdown(folder_path, is_first_layer=True) # 將 Markdown 寫入檔案 with open(file_path, 'w', encoding='utf-8') as md_file: md_file.write(markdown_header + markdown_content) # 關閉錯誤日誌檔案 error_log.close() print(f"Markdown 檔案已儲存於 {file_path}") print(f"錯誤日誌已儲存於 {error_log_path}") ```