我想根据文件名将文件移动到不同的文件夹。 文件名的示例是:
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,所以这里的任何帮助将不胜感激!
最佳答案
这个怎么样?您基本上可以使用字符串成员资格测试(即 if d in x
)将目标映射到应该转到这些目标的文件。当然,这假设所有要移动的文件都从 source
文件夹开始,并且所有目标都位于同一文件夹中 ('C:\\Users\\Desktop\\move文件'
)。
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)
关于python - 如何通过将文件名与文件夹名称匹配来将文件移动到不同的目录并移动到相应的文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43502982/