-2

Whenever I try to get current working directory in python on windows with os.getcwd() it shows only the root directory.

for example this directory structure:

root\
ㄴbase\
ㄴㄴfile\
ㄴㄴㄴfile.py\

I use

# files.py
os.getcwd()

output will be:

\---> c:/root\

I want to get c:/root/file

any idea? thanks in advance



+ actually os.getcwd() finds the 'root:\base\' at some point. but in other cases it doesn't find. so I wanted to know the difference.

  • Does this answer your question? [How do you properly determine the current script directory?](https://stackoverflow.com/questions/3718657/how-do-you-properly-determine-the-current-script-directory) – Czaporka Jun 18 '21 at 10:01
  • if you start script or program in `C:/root` then it is your `current working directory` and it doesn't matter that `file.py` is in different place. `current working directory` doesn't mean `script folder` or `project folder` – furas Jun 18 '21 at 11:33
  • @furas no I'm running the file in ```C://root//base``` – Jahyeon Jee Jun 21 '21 at 07:45
  • if `os.getcwd()` shows only `c:/root` then you run code in `c:/root`, not in `c:/root/base`. You can change directory before you run code `cd c:/root/base ; python script.py`, or you can change it after running `os.chdir("c:/root/base")` – furas Jun 21 '21 at 08:54
  • "Whenever I try to get current working directory in python on windows with os.getcwd() it shows only the root directory." - yes, because **that actually is** the current working directory. The thing that you want to get **is not**. – Karl Knechtel Mar 15 '23 at 08:01

1 Answers1

1

Current working directory isn't the path of the script, it's where you are running the script from.

And apparently, you're running your script from c:/root/ directory. If you want the directory of the script use this to get the script path

from os.path import dirname, abspath
script_path = abspath(dirname(__file__))

or run the script from c:/root/base/file to get the path with getcwd().

thakee nathees
  • 877
  • 1
  • 9
  • 16
  • yeah I added something and I of course run the file in that location(c:/base/). but still in some cases it doesn't find. Also, I know the other approach to find where the script is. – Jahyeon Jee Jun 21 '21 at 07:44