6

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.

Alperen
  • 3,772
  • 3
  • 27
  • 49
  • I'm having this exact same issue. Strange part, is the terminal says: FileNotFoundError [Errno 2] No such file or directory: 'path/to/file.py'. But I can option+click on 'path/to/file.py' and it opens the file in VS code. Did you ever find a solution that worked for you? – Ryan Jul 03 '22 at 06:46

4 Answers4

5

You can use the cwd option in your debug configuration, but I would advise you simply don't hard-code the path and use pathlib or os.path to specify the file relative to the location of __file__ (I'm not quite sure why you want to avoid those modules).

Brett Cannon
  • 14,438
  • 3
  • 45
  • 40
  • That is not about avoiding those modules. I thought, normal run and debug should work same, I just didn't want the answers including `os.path` and `pathlib` . But the `cwd` option makes sense. Its default is `${workspaceFolder}`. If `foo_path = "data/foo.txt"`, it works. Or, I can change `cwd` as you suggest. Thank you. – Alperen Mar 26 '19 at 04:53
  • 1
    Didn't work for me, but `"cwd": "${fileDirname}"` did, which isn't mentioned in the link, but here: [set cwd](https://stackoverflow.com/questions/38623138/vscode-how-to-set-working-directory-for-debugging-a-python-program). Note to myself, should I land in this duplicate question, again :) – Spartan Jun 26 '22 at 05:01
  • the pathlib's `p = Path('my.csv').resolve().__str__(); with open(p, 'r') as csv_file:` doesn't helped.. – Yu Da Chi Dec 20 '22 at 10:12
  • @Oleg You probably want `(Path(__file__).parent / 'my.csv').open('r') as csv_file: ...`. And I would advise against calling `__str__()`/`str()` on a path object. Not only is it usually unnecessary (thanks to https://peps.python.org/pep-0519/), it can lead to odd errors if someone passes something like `None` as a file path by accident. If you truly need the string of a path, use `os.fsdecode()`. – Brett Cannon Jan 13 '23 at 20:04
  • @BrettCannonq i have string issues for using Path objects as path - all the time! so much annoying, just take any app from outside the std.lib. as for solution - thanks, i will try! – Yu Da Chi Jan 14 '23 at 21:19
2

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.

John Johnson
  • 543
  • 4
  • 9
0

As for me, I had my main.py in a folder B inside a folder A. If I opened VSCode in folder A, and tried to debug main.py, I got a FileNotFoundExeptionfor 'file.txt'. When I opened VSCode in folder B and did the same, it worked.

folder A
-- folder B
|     main.py
|     file.txt

(Turning Setting Python > Terminal: Execute In File Dir as proposed in another comment did not solve the issue for me)

Anna Madsen
  • 384
  • 3
  • 15
0

I use pathlib, which always works, both runtime and during debugging:

import os
import pathlib

foo_path = os.path.join(pathlib.Path(__file__).parent.absolute(), "..", "foo.txt")

with open(foo_path) as f:
    s = f.read()
    print(s)
FrankyHollywood
  • 1,497
  • 19
  • 18