【发布时间】:2018-06-30 13:21:31
【问题描述】:
我用 Python 编写了一个读取文本文件的小程序。但是,即使文件存在,我也会不断收到 FileNotFoundError。我的代码看似有问题的代码是这样的:
fileEntered = False
while not fileEntered:
try:
fileName = input("Enter file name: ")
file = open(fileName, "r")
fileEntered = True
fileContents = file.readlines()
file.close()
except FileNotFoundError:
print("File not found. Please try again.")
当询问文件时,我输入 randomtext.txt(与程序位于同一文件夹中),但它不断抛出 FileNotFoundError(它不断打印 除了块)。
【问题讨论】:
-
@dmitryro:PYTHONPATH 与
open()无关,仅用于导入。 -
你是如何运行程序的?在 IDE 中?从命令行?
-
当前工作目录用于
open()中的相对文件名。你能print(os.getcwd())并确保你在正确的工作目录中。您可以使用os.chdir()切换到正确的当前工作目录。或者在open()中使用绝对路径名。
标签: python-3.x