Home > Software engineering >  How do I get Python and Python in Visual Studio code to output the sem when using os.getcwd()?
How do I get Python and Python in Visual Studio code to output the sem when using os.getcwd()?

Time:11-26

I wanted to make it easier to edit my code on different devices with different usernames, so I decided to change how my code knows where my files are. Instead of using the entire file path, I decided to use os.getcwd but when I run it in Visual Studio Code I only get C:\Users\Name while when I run it with just python I get C:\Users\Name\Yuna-Discord-Bot. And for both I am using the same code:

import os

test=(os.getcwd())
print(test)
input("Enter to close")

Is there any way to get them to get Visual Studio Code to the same as just python, or vice versa?

CodePudding user response:

os.getcwd() returns the directory where the running file is located if you run the file directly in the terminal or double-click.

However if you run the file in vscode it should be noted that no matter where the file you are running, the cwd you get will still be the workspace instead of the folder where the file is located (even the file is in the deep directory).

It is determined by the way vscode retrieves files.

This is also the reason for the running error in your comments, because your {filePath} is different for the different running way.

You can try interactive Window which is more suitable for your needs.

enter image description here

or you can use debug mode, and add the following line to your launch.json:

"cwd": "${fileDirname}"
  • Related