使用pathlib读取同一目录中的文件时出现Python FileNotFoundError

问题描述 投票:0回答:1

问题:

我正在阅读 Eric Matthes 所著的《Python 速成课程》一书,在尝试使用 Python 读取名为“pi_digits.txt”的文件时遇到了问题。这是我正在使用的代码:

from pathlib import Path

# Specify the path to the 'pi_digits.txt' file
path = Path('pi_digits.txt')

# Read and print the contents of the file
contents = path.read_text()
print(contents)

当我运行此代码时,我收到一条错误消息,指出不存在名为“pi_digits.txt”的文件或目录。不过,我已经确认该文件与我的 Python 脚本位于同一目录中。这是错误作为参考:

Traceback (most recent call last):
  File "c:\Users\username\python_work\files_and_exceptions\file_reader.py", line 8, in <module>
    contents = path.read_text()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0\Lib\pathlib.py", line 1058, in read_text
    with self.open(mode='r', encoding=encoding, errors=errors) as f:
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0\Lib\pathlib.py", line 1044, in open
    return io.open(self, mode, buffering, encoding, errors, newline)
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'

我尝试过的:

我还尝试将文件的路径指定为

files_and_exceptions/pi_digits.txt
,它可以正常工作。但根据这本书,原始代码应该也可以工作。

以下是我采取的故障排除步骤:

  • 检查该文件是否与我的 Python 脚本位于同一目录中。
  • 确保文件名的开头或结尾没有空格,并多次检查拼写。
  • 已验证我对文件的权限具有完全控制权(我可以查看、修改和保存文件)。

尽管采取了这些步骤,问题仍然存在。我不确定还可以尝试什么,非常感谢任何帮助或建议。

python python-3.x file-io pathlib filenotfounderror
1个回答
0
投票

如果您想使用相对路径读取文件中的内容,请确保该文件与您的 python 脚本位于同一目录中。然后用这个:

filename = 'pi_digits.txt'

# Read and print the contents of the file
with open(filename, 'r') as file_object:
    contents = file_object.read()
    print(contents)
© www.soinside.com 2019 - 2024. All rights reserved.