【发布时间】:2021-07-11 06:23:29
【问题描述】:
我对 Python 很陌生,并且正在通过一本书学习。我只是想运行 filereader.py,它只是打开并读取一个文本文件。此文本文件与 python 代码位于同一文件夹中。但是当我运行它时,会出现这个错误:
Error:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'pi_digits.txt'
File "C:\Users\lcsan\Desktop\python_work\Chapter 10\filereader.py", line 1, in <module>
with open('pi_digits.txt') as file_object:
代码如下:
Filereader.py:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
我尝试导入 os 并使用 os.getcwd() 函数查看程序在哪里搜索文本文件。
这是原始目录:(删减了某些部分) C:\Users\*****\Desktop\python_work\Chapter 10'
这是 os.getcwd() 函数的结果: C:\Users\*****\Desktop\python_work'
它似乎是预期目录后面的一个目录。没有其他方法可以通过相对路径访问它还是我真的必须通过 os.chdir() 指示绝对路径?
【问题讨论】:
标签: python python-3.x