2017-04-19 85 views
1

我有文件,我想根據他們的文件名移動到不同的文件夾。文件名的 例子是:如何通過將文件名稱與文件夾名稱進行匹配將文件移動到不同的目錄和相應的文件夾中?

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,所以在這裏的任何幫助將不勝感激!

回答

1

這個怎麼樣?您基本上將目標映射到應該使用字符串成員資格測試進入這些目標的文件(即if d in x)。這當然假設所有要移動的文件都在source文件夾中開始,並且所有的目標位於相同的文件夾('C:\\Users\\Desktop\\move file')中。

source = 'C:\\Users\\Desktop\\test folder' 

dests = os.listdir('C:\\Users\\Desktop\\move file') 

# Map each destination to the files that should go to that destination 
dest_file_mapping = {d: {os.path.join(source, x 
         for x in os.listdir(source) if d in x} for d in dests} 

for dest, files in dest_file_mapping.items(): 
    for f in files: 
     shutil.copy(f, dest) 
+0

當我用這個方法我得到一個權限錯誤:[錯誤13]許可被拒絕:「C:\\用戶\\\\桌面\\目標測試\\ 296_A_H_1」 – Zfrieden

+1

那是因爲你正在訪問一個擁有管理權限打開/編輯/修改的文件。當您打開命令提示符運行您的python腳本時,請考慮右鍵單擊並選擇「以管理員身份運行」 –

相關問題