Python 无法在 IDE 之外打开文本文件 (Windows 10)
我在使用任何涉及打开文本文件的 python 脚本时都遇到这个问题。我尝试过各种 IDE,包括 VSCode 和 PyCharm,一切都按预期工作。但是,一旦我真正运行 python 脚本,它就会关闭(由于打开外部文件时出现错误,通过注释各个代码部分发现)。
这是一个非常简单的脚本,可以在 IDE 中正常运行,但在实际打开 python 文件时却无法运行:
main.py:
print("This is a demo of the problem.")
file = open("demofile.txt", "r") #this line causes an error outside of IDE
print(file.readlines())
file.close()
demofile.txt:
this is line 1
this is line 2
this is line 3
两个文件都存储在 Desktop 中的同一文件夹中,但是当我将代码修改为
import os
try:
file = open("demofile.txt", "r")
file.close()
except:
print(os.path.abspath("demofile.txt"))
print(os.path.abspath("main.py"))
:得到意想不到的输出:
C:\WINDOWS\system32\demofile.txt
C:\WINDOWS\system32\main.py
任何帮助将不胜感激。
I am having this problem with any python script that involves opening a text file. I have tried in various IDEs, including VSCode and PyCharm, and all works as intended. But as soon as I run the python script for real it closes (due to an error opening the external file, as discovered by commenting out various sections of code).
Here is a very simple script which runs fine in the IDE but not when actually opening the python file:
main.py:
print("This is a demo of the problem.")
file = open("demofile.txt", "r") #this line causes an error outside of IDE
print(file.readlines())
file.close()
demofile.txt:
this is line 1
this is line 2
this is line 3
Both files are stored in the same folder in Desktop, however when I modify the code to this:
import os
try:
file = open("demofile.txt", "r")
file.close()
except:
print(os.path.abspath("demofile.txt"))
print(os.path.abspath("main.py"))
I get an unexpected output of:
C:\WINDOWS\system32\demofile.txt
C:\WINDOWS\system32\main.py
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
输出进行寻址
对
并不一定意味着文件存在。
观察:
您想要做的是使用 os.path.exists() 方法:
所以基本上,当您运行该文件时,Python 的工作方式是当前路径为 C :\WINDOWS\system32,因此如果
demofile.txt
不位于此处,则会出现错误。要查看错误类型,只需将其替换
为
Addressing the output
from
The output does not necessarily mean that the files exist.
Observe:
What you want to do is use the
os.path.exists()
method:So basically, when you ran the file, Python is working in a way that the current path is
C:\WINDOWS\system32
, hence ifdemofile.txt
is not located there, you get the error.To see the type of error, simply replace the
with