0

I have a basic python script to open a file. The script and the file being opened are in the same folder.

If I use the command line in the folder, it works just fine, but from VS Code I'm getting a File not found error.

enter image description here

I have set via the preferences the CWD and it put this in my settings.json

"python.testing.cwd": "${fileDirname}",

From the terminal window in VS Code when I run the code (F5) I can see it's even changing directory to where the program is.

(base) C:\Users\Neil>cd "e:\DATA\Projects\Modelling\Long Drop Data" && cmd /C E:\DATA\Dev\MiniConda\python.exe c:\Users\Neil\.vscode\extensions\ms-python.python-2019.6.24221\pythonFiles\ptvsd_launcher.py --default --client --host localhost --port 50397 "e:\DATA\Projects\Modelling\Long Drop Data\read_data.py" "

Can anyone help?

m3r1v3
  • 362
  • 5
  • 19
Neil Walker
  • 6,400
  • 14
  • 57
  • 86
  • Can you share the error message as well? If any other details then `File not found.` – nitishagar Jul 26 '19 at 09:54
  • Yes, sure. I'll update the message. It is simply it is looking in the 'default' folder and not the folder where the script it, for the file so it does not exist. – Neil Walker Jul 26 '19 at 09:59
  • One more thing. What is `launch.json` - can you past that too here. – nitishagar Jul 26 '19 at 10:03
  • 1
    This might be helpful in the configuration. Given `cwd` param for `launch.json`. Ref: https://stackoverflow.com/questions/38623138/vscode-how-to-set-working-directory-for-debug – nitishagar Jul 26 '19 at 10:04
  • Thanks, I'm just opening a single script file not a folder, and I didn't really want to go down the route of having to create an entire launcher file every time I want to do something like this. – Neil Walker Jul 26 '19 at 10:11

2 Answers2

1

You can either specify the current working directory you want in your launch.json or you will need to calculate the location of the file you want to read more concretely, e.g. pathlib.Path(__file__).with_name(filename) if the file is kept next to the Python file. (The testing setting only affects when you run tests via the extension.)

Brett Cannon
  • 14,438
  • 3
  • 45
  • 40
1

filename = 'file.csv' facing the same issue I stumbled to a solution and it worked without any complex reworking of settings. In my case the file is not being "trusted" nor is the folder within vs code. When I opened the folder from the file menu (shortcut ctrl+k followed by ctrl+o) I was prompted to trust the authors of the folder/its contents. Thereafter my python code works.

Yan
  • 11
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – xlmaster Mar 03 '23 at 17:15