You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中fnmatch匹配目录文件与txt列表文件无结果问题排查

问题分析与解决办法

匹配失败的核心原因

readlines()读取文件时会保留每行末尾的换行符\n,导致你拿到的line内容比实际文件名多了一个换行标记。比如文件里写的是test.txt,读出来后变成test.txt\n,自然和目录里的test.txt匹配不上。

修复现有代码

只需要在读取每行时去掉换行符和首尾空白即可:

import fnmatch
import os 

A1_dir = 'C:/users/alexd/kobe'

# 读取文件时清理每行的换行符与空白
with open('C:/users/alexd/kobe/newoutput.txt', 'r') as f:
    Lines = [line.strip() for line in f.readlines()]

for file in os.listdir(A1_dir):
    for line in Lines: 
        if fnmatch.fnmatch(file, line):
            print(f"got one:{file}")

更高效的实现方案

如果你的newoutput.txt里是精确文件名(不是通配符),完全没必要用fnmatch,直接用集合做匹配更高效,还能顺便实现文件复制需求:

import os
import shutil

A1_dir = 'C:/users/alexd/kobe'
target_dir = '你的目标文件夹路径'  # 替换成实际要复制到的目录

# 读取目标文件名到集合,自动去重并过滤空行
with open('C:/users/alexd/kobe/newoutput.txt', 'r') as f:
    target_files = {line.strip() for line in f if line.strip()}

for file_name in os.listdir(A1_dir):
    source_path = os.path.join(A1_dir, file_name)
    # 只处理文件(跳过目录),且文件名在目标列表中
    if os.path.isfile(source_path) and file_name in target_files:
        shutil.copy2(source_path, target_dir)
        print(f"已复制文件: {file_name}")

方案优势

  • 集合查找是O(1)时间复杂度,远快于双重循环遍历列表
  • 加入os.path.isfile()判断,避免误操作目录
  • shutil.copy2()会保留文件元数据(创建时间、修改时间等),比手动复制更可靠
  • 自动过滤空行,避免无效匹配

内容的提问来源于stack exchange,提问作者alexdobrenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:10:01