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

Python读取文件报错FileNotFoundError:找不到pi_digits.txt文件求助

问题解决方法

一、先修复代码中的语法错误

你的代码里file_object.read缺少括号,这会导致contents存储的是函数对象而非文件内容,修正后代码如下:

"""A simple file reader that accesses the pi_digits text file and prints it out."""

# utf-8 is the standard encoding for txt files.
with open('pi_digits.txt', encoding='utf-8') as file_object:
    contents = file_object.read()  # 添加括号调用read方法

print(contents)

二、解决FileNotFoundError问题

在确认文件名无拼写错误的前提下,问题主要出在文件路径匹配上,可按以下方式排查:

  • 检查当前工作目录:Python默认会在当前运行脚本的工作目录查找文件,先运行这段代码查看当前工作目录:

    import os
    print(os.getcwd())
    

    确认pi_digits.txt是否存放在这个目录中,若不在,要么把文件移到该目录,要么修改open()中的路径。

  • 使用绝对路径:如果文件不在当前工作目录,直接填写文件的绝对路径(注意不同系统路径格式差异):

    • Windows示例:open('C:/Users/YourName/Documents/pi_digits.txt', encoding='utf-8')
    • Linux/macOS示例:open('/home/YourName/Documents/pi_digits.txt', encoding='utf-8')
  • 使用相对路径:如果文件和脚本不在同一目录但有固定层级关系,比如文件在脚本所在目录的data子文件夹里,可写:

    open('data/pi_digits.txt', encoding='utf-8')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:52:07