我可以简化模式匹配文件并将其复制到文件夹进行排序吗?



所以我是一个编码新手,而不仅仅是Python。

我编写了一些代码来整理文件并将它们复制到单独的文件夹中,这样我就可以更轻松地将正确的文件发送给正确的收件人。

这些文件被转储到一个文件夹中,使用搜索功能变得乏味。

因此,在一些错误的启动之后,这段代码可以工作并完成它的工作,但我必须为每个收件人复制并粘贴这些代码块并更改参数。

我只是想知道是否有一种更简化的方法,因为这样做似乎很笨拙。

import os, shutil
dir = ('{the directory the files get dumped into}')
pattern = 'Karl H. Preusse'
matching_files_Karl = [f for f in os.listdir(dir) if pattern in f]
dest_dir = '{the directory the files get dumped into}\Karl'
for file_name in matching_files_Karl:
full_Karl_File_Name = os.path.join(dir, file_name)
if os.path.isfile(full_Karl_File_Name):
shutil.copy(full_Karl_File_Name, dest_dir)

pattern = 'Rom'
matching_files_Rom = [f for f in os.listdir(dir) if pattern in f]
dest_dir = '{the directory the files get dumped into}\ROM'
for file_name in matching_files_Rom:
full_Rom_File_Name = os.path.join(dir, file_name)
if os.path.isfile(full_Rom_File_Name):
shutil.copy(full_Rom_File_Name, dest_dir)

pattern = 'Hochschule'
matching_files_Hochschule = [f for f in os.listdir(dir) if pattern in f]
dest_dir = '{the directory the files get dumped into}\Heldele\Hochschule'
for file_name in matching_files_Hochschule:
full_Hochschule_File_Name = os.path.join(dir, file_name)
if os.path.isfile(full_Hochschule_File_Name):
shutil.copy(full_Hochschule_File_Name, dest_dir)
import os
import shutil
dir = ('{the directory the files get dumped into}')
files = os.listdir(dir)
user_data = [
('Karl H. Preusse', 'dest dir for Karl'),
('Rom', 'dest dir for Rom'),
]
for pattern, dest_dir in user_data:
matching_files = [f for f in files if pattern in f]
for filename in matching_files:
full_filename = os.path.join(dir, filename)
if os.path.isfile(full_filename):
shutil.copy(full_filename, dest_dir)

最新更新