用 Python 寫一個自動整理文件的腳本很簡單,核心思路是:按文件后綴(如 .jpg
、.pdf
)將文件分類,移動到對應的文件夾(如「圖片」「文檔」)中。以下是一個實用的實現方案,新手也能輕松修改和使用。
腳本功能
將指定文件夾(比如「下載」文件夾)中的所有文件,按類型自動分類到子文件夾中,例如:
- 圖片(.jpg, .png, .gif 等)→
圖片/
- 文檔(.pdf, .docx, .xlsx 等)→
文檔/
- 視頻(.mp4, .avi 等)→
視頻/
- 其他未定義類型 →
其他文件/
實現代碼
import os
import shutildef organize_files(target_dir):# 定義文件類型與對應文件夾的映射(可根據需求擴展)file_categories = {'圖片': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp'],'文檔': ['.pdf', '.docx', '.doc', '.xlsx', '.xls', '.pptx', '.ppt', '.txt', '.md'],'視頻': ['.mp4', '.avi', '.mov', '.mkv', '.flv'],'音頻': ['.mp3', '.wav', '.flac', '.m4a'],'壓縮包': ['.zip', '.rar', '.7z', '.tar', '.gz'],'程序': ['.exe', '.msi', '.py', '.java', '.cpp', '.html', '.css', '.js']}# 遍歷目標文件夾中的所有項目for item in os.listdir(target_dir):item_path = os.path.join(target_dir, item)# 跳過文件夾(只處理文件)if os.path.isdir(item_path):continue# 獲取文件后綴(轉為小寫,避免大小寫問題)file_ext = os.path.splitext(item)[1].lower()# 確定文件所屬類別category = '其他文件' # 默認類別for cat, exts in file_categories.items():if file_ext in exts:category = catbreak# 創建對應的類別文件夾(如果不存在)category_dir = os.path.join(target_dir, category)os.makedirs(category_dir, exist_ok=True)# 處理同名文件(避免覆蓋)target_path = os.path.join(category_dir, item)counter = 1while os.path.exists(target_path):# 例如:test.jpg → test(1).jpgname, ext = os.path.splitext(item)target_path = os.path.join(category_dir, f"{name}({counter}){ext}")counter += 1# 移動文件到目標文件夾shutil.move(item_path, target_path)print(f"已移動:{item} → {category}/")if __name__ == "__main__":# 替換為你要整理的文件夾路徑(注意斜杠方向)# Windows示例:r"C:\Users\你的用戶名\Downloads"# Mac/Linux示例:"/Users/你的用戶名/Downloads"target_directory = r"C:\Users\你的用戶名\Downloads"# 檢查路徑是否存在if not os.path.exists(target_directory):print(f"錯誤:路徑不存在 → {target_directory}")else:print(f"開始整理文件夾:{target_directory}")organize_files(target_directory)print("整理完成!")
使用方法
-
修改路徑:將代碼中
target_directory
的值改為你要整理的文件夾路徑(比如下載文件夾)。- Windows 路徑格式:
r"C:\Users\你的用戶名\Downloads"
(注意前面的r
不能少) - Mac/Linux 路徑格式:
"/Users/你的用戶名/Downloads"
- Windows 路徑格式:
-
運行腳本:保存為
file_organizer.py
,在終端執行python file_organizer.py
。
自定義擴展
- 添加更多類型:在
file_categories
字典中添加新的類別和對應的后綴,例如:
'電子書': ['.epub', '.mobi']
- 修改文件夾名稱:直接修改字典的鍵(如將「圖片」改為「Images」)。
- 排除特定文件:如果有不想移動的文件(如
README.txt
),可在遍歷前添加判斷跳過。
注意事項
- 首次使用建議先備份文件,避免誤操作。
- 腳本會跳過已存在的分類文件夾(如已有的「圖片」文件夾),不會遞歸處理子文件夾。
- 遇到同名文件時,會自動在文件名后加編號(如
test(1).jpg
),避免覆蓋。
用這個腳本,從此告別雜亂的下載文件夾啦!