When reading or writing files in a Python script using relative paths (e.g., data.txt), the program searches for them based on the “Current Directory (Current Working Directory).” Therefore, knowing where your program is currently running and moving the working location are fundamental operations for file handling.
This article explains how to get and change the current directory using the standard library os module.
1. Getting the Current Directory: os.getcwd()
To get the current working directory, use the os.getcwd() function. (CWD stands for Current Working Directory).
Syntax:
import os
current_path = os.getcwd()
Specific Usage Example
Let’s display the location where the script is executed.
import os
# Get and display the current directory
path = os.getcwd()
print(f"Current Directory: {path}")
Output Example:
Current Directory: /Users/username/projects/python-app
(On Windows, it would look like C:\Users\username\projects\python-app)
2. Changing the Current Directory: os.chdir()
To move the working directory to another location, use the os.chdir() function. (CHDIR stands for Change Directory). Pass the destination path (absolute or relative) as a string argument.
Syntax:
import os
os.chdir("path_to_move")
Specific Usage Example
Here is a program that moves to the parent directory (one level up) and confirms that the location has changed.
import os
print(f"Before move: {os.getcwd()}")
# Move to parent directory ".."
# You can also specify an actual folder name (e.g., "data_folder")
try:
os.chdir("..")
print("Directory moved.")
except FileNotFoundError:
print("The specified directory was not found.")
print(f"After move: {os.getcwd()}")
Output Example:
Before move: /Users/username/projects/python-app
Directory moved.
After move: /Users/username/projects
Note on Path Specification (For Windows Users)
The backslash (\), which is the path separator in Windows, is treated as an escape sequence in Python strings. Therefore, it is recommended to use one of the following methods when specifying paths:
- Use Raw Strings (Recommended): Add
rat the beginning to treat\as a literal character.Pythonos.chdir(r"C:\Users\Name\Documents") - Use Forward Slashes: Python recognizes
/as a path separator even on Windows.Pythonos.chdir("C:/Users/Name/Documents") - Use Double Backslashes: Escape by doubling
\\.Pythonos.chdir("C:\\Users\\Name\\Documents")
Summary
os.getcwd(): Returns the current working directory as a string.os.chdir(path): Changes the current working directory to the specified path.
When performing file operations, it is important to manage your working location using these functions to avoid reading or writing files in unintended locations.
