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

文件打开问题:指定绝对路径后脚本仍从当前工作目录读取文件

问题:读取指定目录文件时出现文件找不到错误

我曾参考过《How to open a list of files in Python》一文,但我的问题未被覆盖。

以下是我的代码:

path = "C:\\test\\test5\\"
files = os.listdir(path)
fileNames = []

for f in files:
    fileNames.append(f)
    
for fileName in fileNames: 
    pathFileName = path + fileName  
    print(f"This is the path: {pathFileName}") 
    fin = open(pathFileName, 'rt')

    texts = []

    with open(fileName) as file_in:
        # read file text lines into an array    
        for text in file_in:
            texts.append(text)

        for text in texts:
            print(text)

文件aaaatest.txt位于C:\test\test5,运行脚本后输出:

This is the path: C:\test\test5\aaaatest.txt
Traceback (most recent call last):
  File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
    with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'aaaatest.txt'

若将aaaatest.txt复制一份到当前工作目录(cwd),再次运行脚本:

This is the path: C:\test\test5\aaaatest.txt
A triple AAA test
This is the path: C:\test\test5\AALTONEN-ALLAN_PENCARROW_PAGE_1.txt
Traceback (most recent call last):
  File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
    with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'AALTONEN-ALLAN_PENCARROW_PAGE_1.txt'

我疑惑为何脚本显示的路径是C:\test\test5,却仅能从当前工作目录读取文件?


解决办法

问题核心是代码里的关键错误:你已经拼出了完整的文件路径pathFileName,但真正打开文件时却用了仅含文件名的fileName。Python的open函数如果只传文件名,会默认在当前脚本运行的工作目录查找文件,这就是为什么只有把文件复制到工作目录才能读取的原因。

另外代码还存在冗余和资源泄漏问题,比如手动创建fileNames列表完全没必要,以及打开了fin却未关闭。

修正后的代码如下:

import os

path = "C:\\test\\test5\\"
# 直接遍历目录下的文件,无需额外存储列表
for fileName in os.listdir(path): 
    # 用os.path.join拼接路径,适配不同系统的路径分隔符,比手动加斜杠更可靠
    full_path = os.path.join(path, fileName)  
    print(f"This is the path: {full_path}") 

    # 用完整路径打开目标目录下的文件
    with open(full_path, 'r') as file_in:
        # 一行读取所有行,替代手动循环append的冗余写法
        texts = file_in.readlines()

    for text in texts:
        print(text)

关键修正点:

  • 将with open(fileName)改为with open(full_path),直接用完整路径访问目标目录的文件
  • 用os.path.join拼接路径,避免手动拼接斜杠可能出现的格式错误
  • 移除冗余的fileNames列表,直接遍历os.listdir结果
  • 删除未使用的fin文件对象,避免资源浪费

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:36:05