如何让Python查找以指定固定前缀命名的文件?
查找指定前缀的文件解决方案
当然可以实现,下面是两种简单直接的方法:
方法一:使用glob模块(推荐)
glob模块原生支持通配符匹配,非常适合这种按前缀查找文件的场景,能直接处理带空格的路径:
import glob import os # 目标文件夹路径(用原始字符串r""避免反斜杠转义问题) target_dir = r"C:\Users\Soc DRU USD 002" # 固定前缀 prefix = "Banco Interlocutor FB03_" # 构造匹配模式:前缀+任意字符+.png pattern = f"{target_dir}\\{prefix}*.png" # 获取所有符合条件的文件路径 matching_files = glob.glob(pattern) # 处理结果 if matching_files: # 若存在多个匹配文件,取修改时间最新的(避免误选旧文件) latest_file = max(matching_files, key=lambda x: os.path.getmtime(x)) print(f"找到目标文件:{latest_file}") else: print("未找到符合前缀的文件")
方法二:使用os模块手动遍历
如果需要更灵活的判断逻辑(比如同时过滤文件类型、排除文件夹),可以用os.listdir遍历目录:
import os target_dir = r"C:\Users\Soc DRU USD 002" prefix = "Banco Interlocutor FB03_" matching_files = [] for filename in os.listdir(target_dir): # 判断文件名前缀和后缀,同时确保是文件而非子文件夹 if filename.startswith(prefix) and filename.endswith(".png"): full_path = os.path.join(target_dir, filename) if os.path.isfile(full_path): matching_files.append(full_path) if matching_files: latest_file = max(matching_files, key=lambda x: os.path.getmtime(x)) print(f"找到目标文件:{latest_file}") else: print("未找到符合前缀的文件")
注意事项
- 若目录下存在多个符合前缀的文件,优先按修改时间取最新的是更稳妥的选择
- Windows路径中的空格无需额外处理,用原始字符串
r""或双反斜杠即可规避转义错误
内容的提问来源于stack exchange,提问作者Luciano Capua
相关产品推荐
相关产品推荐

