Riggun
Riggun

Reputation: 315

Visual Studio Code can't run Python propertly

After windows re-installation I've met a strange problem with running python scripts from Visual Studio Code. I can run simple helloworlds but if im trying to open a file for example simple txt from the same directory as working script, it returns me that file is not found. At the same time the same script works well if I run it just from command line. Ive discovered that the problem is exactly with VSCode while running script from VSC it cant properly determine working directory of the script. Ive never met such a problem before and I cant find a solution.

Upvotes: 1

Views: 131

Answers (2)

Steven-MSFT
Steven-MSFT

Reputation: 8431

You are using the relative path to reference the file and the relative path depends on the cwd. You can find the difference between the terminal:

enter image description here

So you can use the absolute path to avoid it or to modify the cwd. But both of them are not suggested. You should depend on the default cwd(workspace folder path) to reference the file.

Such as, if you move the file under the workspace folder directly, your code should work, otherwise, you need to add the prefix path before the file you want to using.

Upvotes: 0

Krishay R.
Krishay R.

Reputation: 2814

Here are a couple solutions I found:

  1. Try to give the exact location of the file. Something like this: C://user/desktop/folder/file.txt
  2. Create a launch.json file.

... For most debugging scenarios, creating a launch configuration file is beneficial because it allows you to configure and save debugging setup details. VS Code keeps debugging configuration information in a launch.json file located in a .vscode folder in your workspace (project root folder) ...

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Current File",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal",
      "cwd": "${workspaceFolder}/${relativeFileDirname}"
    }
  ]
}

Upvotes: 1

Related Questions