So I am writing a code where I need to import a file. Both the python code file and the file I need to import are in the same directory thus I haven't specified the whole path.
The code works fine in IDLE but I get an error in Visual Studio Code
I added the line "print(few)" to check if it worked in IDLE. It does print it.
import random
infile=open("StatesANC.txt","r")
print("few")
The error I get in Visual Studio is as follows:-
Traceback (most recent call last):
File "f:/SKKU/study/ISS3178 - Python/11/Lab Assignment 11.py", line 2, in <module>
infile=open("StatesANC.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'StatesANC.txt'
As others have pointed out, the problem is that the default working directory for IDLE and Visual Studio Code may be different.
One way to test this is to include the following at the beginning of your script:
import os
cwd = os.getcwd()
print(cwd)
If that is actually the case, you could change your working directory to the one of your script (whose file path is stored in the special variable __file__
) with:
import os
script_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_path)
This code should be put before opening the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With