如何在Python中动态获取含"weekly time report"的Excel文件路径(忽略日期)
动态匹配含指定关键词的Excel文件路径
可以通过模糊匹配或正则表达式实现,以下是两种实用方案:
方案1:用Pathlib的glob快速模糊匹配
利用通配符*匹配日期部分的任意字符,快速定位目标文件:
from pathlib import Path import shutil import os # 替换为你的实际桌面路径 search_dir = Path(r'C:\Users\你的用户名\Desktop') # 匹配包含"weekly time report"的xlsx文件(注意原代码里的xslx是笔误,正确后缀为xlsx) matching_files = list(search_dir.glob('*weekly time report*.xlsx')) if matching_files: # 若存在多个匹配文件,按修改时间倒序排序,取最新的一份 matching_files.sort(key=lambda x: os.path.getmtime(x), reverse=True) source_path = matching_files[0] # 动态生成目标路径,保留原文件名 dest_path = Path(r'networkdrive') / source_path.name # 执行复制操作 shutil.copyfile(source_path, dest_path) print(f"文件已复制:{source_path} -> {dest_path}") else: print("未找到包含'weekly time report'的Excel文件")
方案2:用正则表达式精确匹配
如果需要严格匹配「关键词+日期」的格式(避免匹配到无关文件),可以用正则:
from pathlib import Path import shutil import re import os search_dir = Path(r'C:\Users\你的用户名\Desktop') # 正则规则:匹配"weekly time report"后接空格+数字.数字.数字的格式,忽略大小写 pattern = re.compile(r'weekly time report\s+\d+\.\d+\.\d+\.xlsx', re.IGNORECASE) matching_files = [] for file in search_dir.glob('*.xlsx'): if pattern.match(file.name): matching_files.append(file) if matching_files: # 按修改时间取最新文件 matching_files.sort(key=lambda x: os.path.getmtime(x), reverse=True) source_path = matching_files[0] dest_path = Path(r'networkdrive') / source_path.name shutil.copyfile(source_path, dest_path) print(f"最新文件已复制:{source_path} -> {dest_path}") else: print("未找到符合格式的'weekly time report' Excel文件")
注意事项
- 务必替换
search_dir为你的实际桌面路径 - 原代码中的
xslx是拼写错误,正确的Excel文件后缀为xlsx - 若目标目录
networkdrive不存在,可添加dest_path.parent.mkdir(exist_ok=True)自动创建目录
内容的提问来源于stack exchange,提问作者Jonnyboi
相关产品推荐
相关产品推荐

