![](/img/trans.png)
[英]python: can i move a file based on part of the name to a folder with that name
[英]Python: Move files to folder based on Part of File name
文件夾包含文件
現在我想將 (1,2,3)(4,5)(6,7) 移動到每個文件夾。 必須根據文件名創建文件夾並移動相應的文件。 以下代碼有效,但文件名在字符范圍 x:y 中,但在文件名示例上方不起作用。所以需要對文件名進行一些修改。謝謝。
import os, shutil
os.chdir("<abs path to desktop>")
for f in os.listdir("folder"):
folderName = f[0:10]
if not os.path.exists(folderName):
os.mkdir(folderName)
shutil.copy(os.path.join('folder', f), folderName)
else:
shutil.copy(os.path.join('folder', f), folderName)
假設文件將始終以“_number”結尾
import os, shutil
os.chdir("<abs path to desktop>")
for f in os.listdir("folder"):
folderName = f[0:-2]
if not os.path.exists(folderName):
os.mkdir(folderName)
shutil.copy(os.path.join('folder', f), folderName)
else:
shutil.copy(os.path.join('folder', f), folderName)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.