How to get the current working directory in Python
Path.cwd() returns a Path object. os.getcwd() returns a string — both are equivalent.
from pathlib import Path
print(Path.cwd()) # e.g. /Users/alice/projects/fooThe 'current working directory' is the folder Python was launched from — NOT the folder containing the script. `python foo.py` from /tmp makes cwd='/tmp' regardless of where foo.py lives on disk.
For the DIRECTORY THE SCRIPT LIVES IN, use Path(__file__).parent. This is what you almost always want when opening a config or data file that ships with your code — Path.cwd() breaks the moment someone runs your script from another folder.
Change directory with os.chdir(path). Better yet: pass absolute paths so you never depend on cwd.
Variations
Directory of THIS script
from pathlib import Path
HERE = Path(__file__).parent
data_file = HERE / "data.json"Portable — works no matter where the script is run from.
os.getcwd (legacy)
import os
print(os.getcwd())Same value, returned as a string not a Path.
Change directory
import os
os.chdir("/tmp")
print(Path.cwd()) # /tmpGlobal side effect — affects the whole process.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.