To find the current working directory and the directory of a specific file in Python, use the os
and pathlib
modules. Here’s how:
1. Current Working Directory
The directory your script is executing from (may differ from the file’s directory).
Using os
:
import os
current_dir = os.getcwd() # "get current working directory"
print(f"Current directory: {current_dir}")
Using pathlib
(Python 3.4+):
from pathlib import Path
current_dir = Path.cwd()
print(f"Current directory: {current_dir}")
2. File’s Directory
The directory containing the currently executing script or file.
Using os
:
import os
# Path of the current file (e.g., /path/to/script.py)
file_path = os.path.abspath(__file__)
# Directory of the file
file_dir = os.path.dirname(file_path)
print(f"File's directory: {file_dir}")
Using pathlib
:
from pathlib import Path
file_dir = Path(__file__).resolve().parent # .resolve() handles symlinks
print(f"File's directory: {file_dir}")
Key Notes
__file__
: A built-in variable representing the path to the current script.- Not available in interactive shells (e.g., Jupyter notebooks).
- Always use
os.path.abspath(__file__)
orPath(__file__).resolve()
to get an absolute path. - Difference:
- Current working directory (
os.getcwd()
): Where the script is run from. - File’s directory (
Path(__file__).parent
): Where the script itself resides.
Example Workflow
Suppose your script /home/user/project/script.py
is run from /home/user
:
import os
from pathlib import Path
# Current directory (where the script is run)
print(os.getcwd()) # Output: /home/user
# File's directory (where script.py resides)
print(Path(__file__).resolve().parent) # Output: /home/user/project
Common Use Cases
- Loading Files Relative to the Script:
from pathlib import Path
script_dir = Path(__file__).resolve().parent
data_path = script_dir / "data.csv" # Path to data.csv in the script's directory
- Switching the Working Directory:
import os
os.chdir(Path(__file__).resolve().parent) # Change working directory to the script's dir
Troubleshooting
FileNotFoundError
: Ensure the file exists and__file__
is defined (not applicable in shells).- Symlinks: Use
resolve()
inpathlib
to resolve symbolic links to the actual path.
Use os
for compatibility with older Python versions, and pathlib
for modern, object-oriented path handling.