我使用在线编译器在我的桌面中使用python访问文档。
file = open(r"C:UsersSUNDesktopoops in python.txt")
for i in file:
print(i)
file.close()
当我运行这段代码时,我得到这个错误
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\SUN\Desktop\oops in python.txt'
我检查了文件名和目录。都是对的。我还是得到同样的错误
为什么我得到这个错误?
当我在离线编译器中运行这段代码时,它可以工作。我得到了所需的输出。
这是因为在线编译器无法访问您的系统文件。你正在使用的网站为你创建一个会话,并在他们的服务器上运行你的代码,所以你只能在会话期间访问你创建并保存到他们服务器上的文件。
我认为正确的文件名是"loops in python.txt
";而不是"oops in python.txt
"。
你是不是错过了一开始的l
?
- 在windows上,您也可以使用正斜杠(
/
)。 with open
确保自动关闭文件。例如:
with open("C:/Users/SUN/Desktop/loops in python.txt") as f:
for l in f:
...