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

Python3读取文件夹文件触发FileNotFoundError错误求助

解决FileNotFoundError:无法定位文件的问题

嘿,我看到你在读取指定文件夹里的文件时遇到了FileNotFoundError: [Errno 2] No such file or directory,咱们来一步步排查并解决这个问题。

问题根源

你代码里的核心问题出在文件路径的生成上:

  • os.listdir(prefix_path)返回的只是目标文件夹里的纯文件名(比如data1.txt),而不是完整路径
  • 当你用os.path.abspath(f)处理这些文件名时,Python会把当前工作目录和文件名拼接,而不是你指定的prefix_path,这就导致程序去错误的路径找文件,自然找不到了。

解决方案

这里有两种简单有效的修正方式,你可以选一种适合你的:

方式一:用os.path.join()拼接完整路径

这是最稳妥的标准做法,确保每个文件的路径都基于你指定的前缀路径生成:

import os
prefix_path = "C:/Users/mpotd/Documents/GitHub/Python-Sample-codes/Mayur_Python_code/Question/wx_data/"

# 用with语句管理目标文件,自动关闭更安全
with open('MissingPrcpData.txt', 'w') as target_file:
    # 修正:用os.path.join把前缀路径和文件名拼接成完整路径
    file_array = [os.path.join(prefix_path, f) for f in os.listdir(prefix_path) if f.endswith('.txt')]
    file_array.sort()

    # 直接遍历完整路径列表,不用再处理索引
    for file_path in file_array:
        # 同样用with语句打开源文件,避免资源泄漏
        with open(file_path, 'r') as source_file:
            # 这里写你的读取/处理逻辑,比如读取内容写入目标文件
            content = source_file.read()
            target_file.write(content + '\n')

方式二:改用glob.glob()直接获取完整路径

glob模块可以直接帮你匹配指定路径下的文件,返回的就是完整路径,代码更简洁:

import os
import glob
prefix_path = "C:/Users/mpotd/Documents/GitHub/Python-Sample-codes/Mayur_Python_code/Question/wx_data/"

with open('MissingPrcpData.txt', 'w') as target_file:
    # 用glob直接获取所有txt文件的完整路径
    file_array = glob.glob(os.path.join(prefix_path, '*.txt'))
    file_array.sort()

    for file_path in file_array:
        with open(file_path, 'r') as source_file:
            content = source_file.read()
            target_file.write(content + '\n')

额外注意事项

  • 先确认prefix_path的拼写完全正确,比如有没有大小写错误、文件夹名称写错
  • 确保你的Python程序有访问该文件夹的权限(比如Windows下的权限限制)
  • 尽量用with语句管理文件句柄,它会自动帮你关闭文件,避免忘记关闭导致的资源泄漏或文件损坏问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:35:46