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

Python递归搜索文本文件删除指定User-ID 解决FileNotFoundError问题

修复方案

核心思路

原报错原因是脚本仅在固定根目录下查找文件,未递归遍历子目录。我们可以先遍历/home/user/excel/report/下的所有子目录,提前构建「不带后缀的文件名→文件完整路径」的映射表,后续处理时直接查表获取正确路径即可。

修复后完整代码

import os
import pandas as pd

# 定义根目录常量,避免重复书写出错
ROOT_PATH = "/home/user/excel/report/"

# 第一步:递归遍历所有子目录,构建文件名到完整路径的映射
file_path_map = {}
for root, dirs, files in os.walk(ROOT_PATH):
    for file in files:
        # 只处理后缀为.txt的文件
        if file.endswith(".txt"):
            # 去掉后缀作为映射的key,匹配Excel里的File Name列
            file_name_without_suffix = os.path.splitext(file)[0]
            full_path = os.path.join(root, file)
            # 如果存在重名文件,会存储最后一个遍历到的路径;如果需要处理所有重名文件,可把value改为列表存储所有路径
            file_path_map[file_name_without_suffix] = full_path

# 第二步:读取Excel数据
data = pd.read_excel("data.xlsx")
d = dict(zip(data["File Name"], data["User-ID"]))

# 第三步:遍历处理每个文件
for file_name, user_id in d.items():
    # 先判断文件是否在映射表中,不存在则跳过并提示
    if file_name not in file_path_map:
        print(f"未找到文件:{file_name}.txt,跳过处理")
        continue
    target_path = file_path_map[file_name]
    # 读取文件内容
    with open(target_path, "r", encoding="utf-8") as f:
        contents = f.read()
    # 替换User-ID(如果需要删除包含User-ID的整行,可替换为下面注释的代码)
    new_content = contents.replace(user_id, "")
    # 若要删除包含User-ID的整行,使用以下代码:
    # lines = contents.splitlines()
    # new_lines = [line for line in lines if user_id not in line]
    # new_content = "\n".join(new_lines)
    # 写入修改后的内容
    with open(target_path, "w", encoding="utf-8") as f:
        f.write(new_content)
    print(f"已处理文件:{target_path}")

额外说明

  • 代码中添加了编码声明encoding="utf-8",避免读取非ASCII字符的文件时报错
  • 若存在多个子目录下有同名txt文件的情况,可修改映射逻辑,把file_path_map的value改为列表存储所有匹配的路径,遍历处理所有路径即可
  • 原代码的replace逻辑会删除所有匹配的User-ID字符串,如果你实际需要的是删除包含该User-ID的整行,可以使用代码中注释的整行过滤逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 13:54:00