我有文件,我想根據他們的文件名移動到不同的文件夾。文件名的 例子是:如何通過將文件名稱與文件夾名稱進行匹配將文件移動到不同的目錄和相應的文件夾中?
296_A_H_1_1_20070405.pdf
296_A_H_10_1_20070405.pdf
296_A_H_2_1_20070405.pdf
296_A_H_20_1_20070405.pdf
相應的文件夾名稱:
296_A_H_1
296_A_H_2
296_A_H_10
296_A_H_20
我想將文件移動到基於文件名正確的文件夾。例如,296_A_H_1 _1_20070405.pdf應該在296_A_H_1文件夾中。這裏是我到目前爲止的代碼:
import shutil
import os
#filepath to files
source = 'C:\\Users\\Desktop\\test folder'
#filepath to destination folders
dest1 = 'C:\\Users\\Desktop\\move file\\296_A_H_1'
dest2 = 'C:\\Users\\Desktop\\move file\\296_A_H_2'
dest3 = 'C:\\Users\\Desktop\\move file\\296_A_H_10'
dest4 = 'C:\\Users\\Desktop\\move file\\296_A_H_20'
files = [os.path.join(source, f) for f in os.listdir(source)]
#move files to destination folders based on file path and name
for f in files:
if (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_1_")):
shutil.copy(f,dest1)
elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_2_")):
shutil.copy(f,dest2)
elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_10")):
shutil.copy(f, dest3)
elif (f.startswith("C:\\Users\\Desktop\\test folder\\296_A_H_20")):
shutil.copy(f, dest4)
此代碼的工作,但我需要400個文件移動到不同的文件夾,並會寫幾百個ELIF語句。我如何通過將文件名與目標文件夾相匹配並使用shutil將文件複製到該文件夾來實現此目的?我剛開始學習Python,所以在這裏的任何幫助將不勝感激!
當我用這個方法我得到一個權限錯誤:[錯誤13]許可被拒絕:「C:\\用戶\\\\桌面\\目標測試\\ 296_A_H_1」 – Zfrieden
那是因爲你正在訪問一個擁有管理權限打開/編輯/修改的文件。當您打開命令提示符運行您的python腳本時,請考慮右鍵單擊並選擇「以管理員身份運行」 –