Search code examples
pythoncommand-lineoperating-systemgetcwd

os getcwd on command line vs editor


I am calling a python 3.10 file from the Anaconda command line (windows, in a conda environment) and noticed that when os.getcwd() is called within a script via command line, it outputs the root directory (I think this is the correct terminology) rather than the directory of the file from which it is called.

So if I run python C:/Users/u03132tk/Python/MyTool/Script.py on command line, I print C:/Users/u03132tk rather than C:/Users/u03132tk/Python/MyTool.

Is there any way to force the path to derive from the script?

Cheers, Tim

C:/Users/u03132tk/Python/MyTool/Script.py

import os
print (os.getcwd())

Solution

  • When you run a Python script from the command line, os.getcwd() returns the current working directory, which may not necessarily be the directory of the script. The above happens especially when you have different folders in your app root directory

    To get the directory of the script itself, you can use os.path.dirname(os.path.abspath(__file__)) within your script. This will give you the absolute path of the directory containing the script.