根据txt列表,批量快速从文件夹里提取需要的文件
import os
import shutil
def copy_files_by_txt(txt_file, source_folder, destination_folder):
# 读取txt文件中的文件名
with open(txt_file, 'r') as file:
file_names = file.read().splitlines()
# 确保目标文件夹存在,如果不存在则创建
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
# 复制文件
for file_name in file_names:
source_path = os.path.join(source_folder, file_name)
destination_path = os.path.join(destination_folder, file_name)
try:
shutil.copy2(source_path, destination_path)
print(f"已复制文件: {file_name}")
except FileNotFoundError:
print(f"文件不存在: {file_name}")
# 输入txt文件路径、源文件夹路径和目标文件夹路径
txt_file_path = '1.txt'
source_folder_path = '1'
destination_folder_path = '2'
# 调用函数进行复制
copy_files_by_txt(txt_file_path, source_folder_path, destination_folder_path)
print("文件复制完成!")