How to Get Current Directory in Python: Simple Guide
To get the current directory in Python, use
os.getcwd() from the os module or Path.cwd() from the pathlib module. Both return the path of the directory where your Python script is running.Syntax
There are two common ways to get the current directory in Python:
os.getcwd(): Returns the current working directory as a string.Path.cwd(): Returns the current working directory as aPathobject from thepathlibmodule.
python
import os from pathlib import Path # Using os module current_dir_os = os.getcwd() # Using pathlib module current_dir_pathlib = Path.cwd()
Example
This example shows how to print the current directory using both os and pathlib. It demonstrates the output as a string and as a Path object.
python
import os from pathlib import Path # Get current directory using os module current_dir_os = os.getcwd() print(f"Current directory using os: {current_dir_os}") # Get current directory using pathlib module current_dir_pathlib = Path.cwd() print(f"Current directory using pathlib: {current_dir_pathlib}")
Output
Current directory using os: /home/user
Current directory using pathlib: /home/user
Common Pitfalls
One common mistake is confusing the current working directory with the directory of the script file. os.getcwd() and Path.cwd() return the directory where the program runs, which can be different from the script's location if you run the script from another folder.
To get the script's directory, use Path(__file__).parent instead.
python
import os from pathlib import Path # Wrong: assuming current directory is script location print(f"Wrong current dir: {os.getcwd()}") # Right: get script's directory script_dir = Path(__file__).parent print(f"Script directory: {script_dir}")
Quick Reference
| Method | Description | Returns |
|---|---|---|
| os.getcwd() | Current working directory as string | String path |
| Path.cwd() | Current working directory as Path object | Path object |
| Path(__file__).parent | Directory of the running script file | Path object |
Key Takeaways
Use os.getcwd() or Path.cwd() to get the current working directory in Python.
The current working directory is where the program runs, not necessarily where the script is saved.
To get the script's folder, use Path(__file__).parent from pathlib.
Pathlib offers a modern and convenient way to handle paths as objects.
Always be clear whether you want the working directory or the script location.