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.
On the inbuilt terminal, inside vscode:
cd /path_to_your_code_dir/
in my case, it was:
cd /repos/
because my code was here -> ~/repos/main.py
.
(edited)
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:
@ext:ms-python.python execute in the settingsThis eliminates the FileNotFoundError when you know your file is sitting in the right place, and you are pointing in the right direction.
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