Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode Python Debugger FileNotFoundError

Let's define a simple folder structure like this:

project
+---code
|       main.py
|
\---data
        foo.txt

main.py:

foo_path = "./../data/foo.txt"

with open(foo_path) as f:
    s = f.read()
    print(s)

This code works well while running normally using python main.py command, but it throws the following error while debugging using VSCode Python Debugger.

Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: './../data/foo.txt'
  File "C:\Users\user\Workspaces\project\code\main.py", line 3, in <module>
    with open(foo_path) as f:

I am using VSCode with Python 3.7.1 Anaconda version in Windows 10. I know that the file path is like a Linux path, but it works while running normally. I couldn't find any open issue in the GitHub repo of Python VSCode Extension. Is this a common error, or am I doing something wrong?

Also, if I define foo_path = ".\\..\\data\\foo.txt", it behaves same as the previous one. It runs well normally and gives the same error while debugging.

How can I fix this without using extra package like os.path or using the full file path?

EDIT: I tried in Ubuntu 18.04, and it behaves same.

like image 501
Alperen Cetin Avatar asked Jun 23 '26 16:06

Alperen Cetin


1 Answers

Exactly. I faced the same issue, and this is how I fixed mine

On the inbuilt terminal, inside vscode:

  • change the directory to where your code lives. For example:
cd /path_to_your_code_dir/

in my case, it was:

cd /repos/

because my code was here -> ~/repos/main.py

  • Then run the VSCode Python Debugger again

.
(edited)

I found the reason for this error and a better way to fix it

The error occurs because the python debugger executes files in the terminal from the current open folder (by default)
But you can change this behavior, to use execute in the file's directory:

  • Go to vscode settings (or use the shortcut key: ctrl+comma )
  • then search for this @ext:ms-python.python execute in the settings
  • you would see the settings "Execute in File Dir"
  • then check the box, to execute code in file's directory instead of the current open folder
  • go back to your code and re-run (i.e clicking the debugger run button)

This eliminates the FileNotFoundError when you know your file is sitting in the right place, and you are pointing in the right direction.

like image 149
John Johnson Avatar answered Jun 25 '26 05:06

John Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!