目前,我的源檔案夾中有 30 多個.xlsx
檔案。
所有這 30 個檔案都來自亞太地區的不同地區,其中包含IND
,KOR
等關鍵字ASN
。
我的目標是執行以下操作
a) 為每個地區(ASN、KOR 和 IND)創建單獨的檔案夾
b) 將.xlsx
帶有地區關鍵字的檔案復制到適當的檔案夾。
所以,我嘗試了以下
if not os.path.exists('C:\\Users\\test\\Downloads\\output_data\\IND'):
os.mkdir('C:\\Users\\test\\Downloads\\output_data\\IND')
if not os.path.exists('C:\\Users\\test\\Downloads\\output_data\\ASN'):
os.mkdir('C:\\Users\\test\\Downloads\\output_data\\ASN')
if not os.path.exists('C:\\Users\\test\\Downloads\\output_data\\KOR'):
os.mkdir('C:\\Users\\test\\Downloads\\output_data\\KOR')
if not os.path.exists('C:\\Users\\test\\Downloads\\output_data\\ASN_ANZ_KR'):
os.mkdir('C:\\Users\\test\\Downloads\\output_data\\ASN_ANZ_KR')
source = 'C:\\Users\\test\\Downloads\\output_data'
IND = 'C:\\Users\\test\\Downloads\\output_data\\IND'
ASN = 'C:\\Users\\test\\Downloads\\output_data\\ASN'
KOR = 'C:\\Users\\test\\Downloads\\output_data\\KOR'
ASN_ANZ_KR = 'C:\\Users\\test\\Downloads\\output_data\\ASN_ANZ_KR'
files = os.listdir(source)
for f in files:
if ("IND.xlsx" in f):
shutil.move(f, IND)
elif ("ASN.xlsx" in f) or ("ANZ.xlsx" in f):
shutil.move(f, ASN)
elif ("KOR.xlsx" in f):
shutil.move(f, KOR)
elif ("KR.xlsx" in f):
shutil.move(f, ASN_ANZ_KR)
else:
a=0 # do nothing so, assign a dummy value to a variable
雖然上面的代碼運行良好,但還有其他更好的方法來撰寫它嗎?
您可以看到我為創建檔案夾撰寫了多個 if 條件(多次),然后根據通配符復制檔案。
有沒有更好的優雅和有效的方法來完成上述任務?
uj5u.com熱心網友回復:
我會做這樣的事情,這是帶注釋的代碼:
from pathlib import Path
# mapping of filename match pattern to destination directory name
dct = {'IND': 'IND', 'ASN': 'ASN', 'KOR': 'KOR', 'KR': 'ASN_ANZ_KR'}
src = Path(source)
for key, val in dct.items():
for file in src.glob(f'*{key}.xlsx'):
# ensure destination directory exists
dest = src / val
dest.mkdir(exist_ok=True)
# Move the file from source to destination
file.rename(dest / file.name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/506670.html
下一篇:System.NullReferenceException:'物件參考未設定為物件的實體。在處理通過c#編輯的word檔案時