免費建網(wǎng)站 步驟寧波企業(yè)網(wǎng)站seo
這是一個簡單但功能強大的Python腳本,用于遞歸遍歷目錄并將指定格式的文件移動到目標目錄。默認支持移動PDF文件,但也可以通過參數(shù)指定其他文件格式。
功能特點
- 遞歸遍歷源目錄及其所有子目錄
- 支持移動任意指定格式的文件
- 自動處理目標目錄中的文件重名情況
- 詳細的操作日志輸出
- 完整的錯誤處理機制
- 支持命令行參數(shù)配置
系統(tǒng)要求
- Python 3.6 或更高版本
- 操作系統(tǒng):Windows/Linux/MacOS
安裝方法
- 克隆或下載此倉庫
- 進入項目目錄
使用方法
命令行參數(shù)
腳本支持以下命令行參數(shù):
-s
?或?--source
:源目錄路徑(必需)-t
?或?--target
:目標目錄路徑(必需)-e
?或?--ext
:文件擴展名(可選,默認為 'pdf')
基本用法
-
移動PDF文件(默認):
python move_pdfs.py -s "源目錄路徑" -t "目標目錄路徑"
-
移動其他格式文件:
python move_pdfs.py -s "源目錄路徑" -t "目標目錄路徑" -e txt
示例
移動PDF文件:
python move_pdfs.py -s "C:\Users\Documents\source" -t "D:\target"
移動TXT文件:
python move_pdfs.py -s "C:\Users\Documents\source" -t "D:\target" -e txt
移動DOCX文件:
python move_pdfs.py -s "C:\Users\Documents\source" -t "D:\target" -e docx
在代碼中調(diào)用
也可以在Python代碼中直接調(diào)用移動函數(shù):
from move_pdfs import move_files# 移動PDF文件
move_files(source_dir="源目錄路徑", target_dir="目標目錄路徑")# 移動其他格式文件
move_files(source_dir="源目錄路徑", target_dir="目標目錄路徑", file_ext=".txt")
注意事項
- 確保有足夠的權(quán)限訪問源目錄和目標目錄
- 建議在執(zhí)行前備份重要文件
- 如果目標目錄中存在同名文件,腳本會自動添加數(shù)字后綴
- 大量文件移動可能需要一定時間,請耐心等待
- 移動過程中會顯示詳細的操作日志
錯誤處理
- 腳本會捕獲并顯示文件移動過程中的錯誤
- 單個文件的錯誤不會影響其他文件的移動
- 所有錯誤都會在控制臺中顯示詳細信息
具體代碼如下:
import os
import shutil
from pathlib import Path
import argparsedef move_files(source_dir, target_dir, file_ext='.pdf'):"""遞歸遍歷源目錄,移動指定格式的文件到目標目錄Args:source_dir (str): 源目錄路徑target_dir (str): 目標目錄路徑file_ext (str): 要移動的文件擴展名,默認為.pdf"""# 確保文件擴展名格式正確if not file_ext.startswith('.'):file_ext = '.' + file_ext# 確保目標目錄存在if not os.path.exists(target_dir):os.makedirs(target_dir)# 計數(shù)器moved_count = 0# 遍歷源目錄for root, dirs, files in os.walk(source_dir):for file in files:if file.lower().endswith(file_ext.lower()):source_path = os.path.join(root, file)target_path = os.path.join(target_dir, file)# 處理目標路徑中的同名文件if os.path.exists(target_path):base, ext = os.path.splitext(file)counter = 1while os.path.exists(target_path):new_name = f"{base}_{counter}{ext}"target_path = os.path.join(target_dir, new_name)counter += 1try:shutil.move(source_path, target_path)print(f"已移動: {source_path} -> {target_path}")moved_count += 1except Exception as e:print(f"移動文件時出錯: {source_path}")print(f"錯誤信息: {str(e)}")print(f"\n完成! 共移動了 {moved_count} 個{file_ext}文件到 {target_dir}")def parse_arguments():"""解析命令行參數(shù)"""parser = argparse.ArgumentParser(description='移動指定格式的文件到目標目錄')parser.add_argument('--source', '-s', required=True, help='源目錄路徑')parser.add_argument('--target', '-t', required=True, help='目標目錄路徑')parser.add_argument('--ext', '-e', default='pdf', help='文件擴展名(不需要包含點號,默認為pdf)')return parser.parse_args()if __name__ == "__main__":args = parse_arguments()# 執(zhí)行移動操作move_files(args.source, args.target, f'.{args.ext}')