Search code examples
pythonpython-3.xvisual-studio-codepython-idle

Code works in Idle but getting an error in VS Code


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'

Solution

  • Give the full path and it should run from everywhere

    say you are using linux system and your file is in xyz folder in home

    import random
    infile=open("/home/xyz/StatesANC.txt","r")
    print("few")