Vscode-code-runner: Open() function in Python not running

Created on 25 Mar 2017  路  2Comments  路  Source: formulahendry/vscode-code-runner

I have recently started learning python.
I use code runner to run my python code in vc.
I have been trying to use the open('___.txt') function in python but it gives me an error every time.
I ran the code in command prompt and it worked flawlessly.
I assume it's a problem in code runner, although i could be wrong.
Here is my code

#!/usr/bin/python3

def main():
    f = open('nums.txt')
    for line in f.readlines():
        print(line)

if __name__ == "__main__": main()

Here is the error

_Traceback (most recent call last):
File "e:\Python\Projects\Lynda\9.1\open.py", line 8, in
if __name__ == "__main__": main()
File "e:\Python\Projects\Lynda\9.1\open.py", line 4, in main
f = open('nums.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'nums.txt'_

PS - I can assure you that the txt file exists in the same folder. You can check yourself in the screenshots.

ThankYou for your help. :)
I appreciate it.

code

code works

question

Most helpful comment

The problem is that in open('nums.txt'), you are using relative path instead of absolute path. You should not assume the CWD (current working directory). In Code Runner, the CWD is the root folder of workspace, i.e. "e:\Python\Projects\Lynda\". Therefore, two options to fix:

  1. Use absolute path (e:\Python\Projects\Lynda\9.1\nums.txt) or correct relative path (9.1\nums.txt) in open('nums.txt')
  2. Set as below, use the directory of the file as CWD
{
    "code-runner.fileDirectoryAsCwd": true
}

All 2 comments

The problem is that in open('nums.txt'), you are using relative path instead of absolute path. You should not assume the CWD (current working directory). In Code Runner, the CWD is the root folder of workspace, i.e. "e:\Python\Projects\Lynda\". Therefore, two options to fix:

  1. Use absolute path (e:\Python\Projects\Lynda\9.1\nums.txt) or correct relative path (9.1\nums.txt) in open('nums.txt')
  2. Set as below, use the directory of the file as CWD
{
    "code-runner.fileDirectoryAsCwd": true
}

@formulahendry That makes complete sense. Thank you for the help, that fixed my problem.

Was this page helpful?
0 / 5 - 0 ratings