以下是一个示例代码,演示了如何遍历字典列表以在目录中搜索文件并将其复制到新位置:
import os
import shutil
# 定义要搜索的目录
search_directory = '/path/to/search/directory/'
# 定义要复制文件的目标目录
destination_directory = '/path/to/destination/directory/'
# 定义要搜索的文件名列表
files_to_search = [
{'name': 'file1.txt', 'new_name': 'new_file1.txt'},
{'name': 'file2.txt', 'new_name': 'new_file2.txt'},
{'name': 'file3.txt', 'new_name': 'new_file3.txt'}
]
# 遍历字典列表
for file_info in files_to_search:
file_name = file_info['name']
new_file_name = file_info['new_name']
# 构建完整的文件路径
file_path = os.path.join(search_directory, file_name)
# 检查文件是否存在
if os.path.isfile(file_path):
# 构建目标文件的完整路径
destination_path = os.path.join(destination_directory, new_file_name)
# 复制文件到目标目录
shutil.copy(file_path, destination_path)
print(f'已复制文件 {file_name} 到 {destination_path}')
else:
print(f'文件 {file_name} 不存在')
在上面的代码中,我们首先定义了要搜索的目录和目标目录的路径。然后,我们创建了一个字典列表,其中每个字典包含要搜索的文件名和要将其复制到的新位置的文件名。接下来,我们使用os.path.join()
函数构建了搜索文件的完整路径和目标文件的完整路径。然后,我们使用os.path.isfile()
函数检查文件是否存在。如果文件存在,我们使用shutil.copy()
函数将文件复制到目标目录,并打印一条成功复制的消息。如果文件不存在,我们打印一条文件不存在的消息。