Python根据列表在指定目录寻找对应前缀的文件
现在有一个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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
2022-10-27 js图片格式转换(File、blob、二进制)
2022-10-27 CSS的fixed定位失效
2022-10-27 v-for 遍历对象
2021-10-27 C# 菜单条目设计及快捷键设置