现在有一个txt列表,里面包含的是一些文件名,如a,b等等,现在需求是在一个多级文件夹下,需要寻找以a为名字的任何格式文件,如a.001,a.002等等,寻找这个txt列表里包含的文件名的对应文件,复制到指定文件夹下
import os
import shutil
# 读取文件名列表
with open('msg.txt', 'r') as file:
filenames = [line.strip() for line in file]
# 函数用于递归查找文件并复制
def find_and_copy_file(filename, source_folder, destination_folder):
for root, _, files in os.walk(source_folder):
for file in files:
if file.startswith(filename):
source_file_path = os.path.join(root, file)
destination_file_path = os.path.join(destination_folder, file)
if not os.path.exists(destination_file_path):
# 复制文件
shutil.copy2(source_file_path, destination_file_path)
print(f'Found and copied: {filename}')
# 指定的源文件夹和目标文件夹
source_folder = r'D:\DATA\enc'
destination_folder = 'chart'
if not os.path.exists(destination_folder):
os.mkdir(destination_folder)
# 遍历文件名列表并查找和复制文件
for filename in filenames:
find_and_copy_file(filename, source_folder, destination_folder)
标签:前缀,Python,destination,列表,source,file,path,folder,os
From: https://www.cnblogs.com/echohye/p/17793179.html