[Python] os.getcwd() return value

Understanding os.getcwd() in Python

os.getcwd() in Python returns the current working directory, not necessarily the directory containing the curretnly running Python script.

Current Working Directory

It’s the directory from which the Python interpreter is launched from, or the folder the command was executed in.

os.getcwd() depends on where the Python interpreter is started, not the script’s location.

Example Folder Structure

my_project/
├── client/
├── server/
│   └── schemas/
│       └── mysql_schema.sql
└── app.py
  • In the terminal inside the my_project folder and run:

    python app.py

    Inside app.py, calling:

    import os
    print(os.getcwd())

    outputs:

    /path/to/my_project
  • From a different directory, like server:

    cd server
    python ../app.py

    Now, os.getcwd() returns:

    /path/to/my_project/server

Comments