简体   繁体   English

如何在 python 中打开文件?

[英]How to open file in python?

Iam coding in vs code with python3.我用 python3 在 vs 代码中编码。 in the tutorial says that you should write f=open("filename.txt") and then run it and if you want to read it f=open("filename.txt","r") and I write a txt in my computre and I'm sure its exicts in my loptop but every time I run the code it gives me: (FileNotFoundError: [Errno 2] No such file or directory) what should I do?在教程中说你应该写f=open("filename.txt")然后运行它,如果你想读它f=open("filename.txt","r")我在我的计算机,我确定它在我的 loptop 中存在,但每次运行它给我的代码时: (FileNotFoundError: [Errno 2] No such file or directory)我该怎么办?

You can try to change "filename.txt" for the absolute path of that file.您可以尝试将"filename.txt"更改为该文件的绝对路径。 That means you should go to your file and copy the exact complete path from the storage through all directories until reaching it:这意味着您应该将 go 复制到您的文件中,并将确切的完整路径从存储中复制到所有目录,直到到达它:

f=open("filename.txt","r")
f=open(r"C:\\Users\\your_user\\Desktop\\filename.txt","r") #Example of an absolute path, in this case the file is in Desktop but you have to copy the exact path you have

If that doesn't work, the file might be corrupted or defective, so you would have to try other solutions.如果这不起作用,则文件可能已损坏或有缺陷,因此您必须尝试其他解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM