简体   繁体   中英

Python cannot open a text file outside of an IDE (Windows 10)

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.

Addressing the output

C:\WINDOWS\system32\demofile.txt
C:\WINDOWS\system32\main.py

from

import os
try:
    file = open("demofile.txt", "r") 
    file.close()
except:
    print(os.path.abspath("demofile.txt"))
    print(os.path.abspath("main.py"))

The output does not necessarily mean that the files exist.

Observe:

>>> import os
>>> os.path.abspath("filethatdoesnotexist.txt")
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python39\\filethatdoesnotexist.txt'
>>> 

What you want to do is use the os.path.exists() method:

import os
try:
    file = open("demofile.txt", "r") 
    file.close()
except:
    print(os.path.exists("demofile.txt"))
    print(os.path.exists("main.py"))

So basically, when you ran the file, Python is working in a way that the current path is C:\WINDOWS\system32 , hence if demofile.txt is not located there, you get the error.


To see the type of error, simply replace the

except:

with

except Exception as e:
    print(e)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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