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

Python从其他目录打开文本文件出现FileNotFoundError的解决求助

解决FileNotFoundError并打开其他目录文件的方法

你的代码片段:

case 'show' | 'display':
      file = open('files/todos.txt','r')
      todos = file.readlines()
      file.close()
      for i,j in enumerate(todos):
          #print(i,"-",j)
          j = j.strip()
          print(f"{i+1}-{j}")

运行时触发的报错:

Traceback (most recent call last):
  File "C:\Users\kanha\PycharmProjects\pythonProject\venv\main1.py", line 17, in <module>
    file = open('files/todos.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'files/todos.txt'

核心问题

你使用的是相对路径,Python会默认从当前脚本的运行目录查找文件,若目标文件不在该路径下,就会触发找不到文件的错误。要打开其他目录的文件,可采用以下几种写法:


解决方案

1. 直接使用绝对路径

把文件的完整路径写出来,比如目标文件在D:\MyFiles\todos.txt:

# Windows系统用原始字符串避免转义问题
file = open(r'D:\MyFiles\todos.txt','r')
# 或者用正斜杠替代反斜杠
file = open('D:/MyFiles/todos.txt','r')

2. 动态拼接路径(灵活适配脚本位置)

如果文件和脚本的相对位置固定,用os模块获取脚本所在目录,再拼接目标路径,避免脚本移动后路径失效:

import os

# 获取当前脚本的绝对目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接目标文件路径(示例:文件在脚本目录的上级文件夹的files目录下)
file_path = os.path.join(script_dir, '../files/todos.txt')
file = open(file_path, 'r')

3. 推荐:用with语句安全操作文件

不管用哪种路径写法,都建议用with语句管理文件,它会自动关闭文件,避免资源泄漏:

import os

script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, '../files/todos.txt')

with open(file_path, 'r') as file:
    todos = file.readlines()
    for i, j in enumerate(todos):
        j = j.strip()
        print(f"{i+1}-{j}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:40:05