In Python, you can set the current working directory using the os
module. The working directory is the folder in which Python scripts are executed and where files are read or written by default.
Setting the Current Working Directory
To set or change the working directory, use the following steps:
- Import the
os
module. - Use
os.chdir()
to change the working directory.
Syntax
import os
os.chdir(path)
path
: A string representing the new directory path you want to set as the current working directory.
Examples
1. Setting the Current Working Directory
import os
# Set the working directory
os.chdir('/path/to/directory')
# Verify the change
print("Current Working Directory:", os.getcwd())
2. Using a Relative Path
import os
# Move to a directory relative to the current location
os.chdir('../new_folder')
# Verify the change
print("Current Working Directory:", os.getcwd())
3. Getting the Current Working Directory
import os
# Get and print the current working directory
cwd = os.getcwd()
print("Current Working Directory:", cwd)
Important Points
- Path Format:
- Use forward slashes (
/
) on Unix-like systems (Linux, macOS). - On Windows, either use double backslashes (
\\
) or raw strings (prefix the path withr
):os.chdir(r"C:\Users\YourName\Documents")
- Use forward slashes (
- Error Handling:
- If the directory does not exist,
os.chdir()
raises aFileNotFoundError
.try: os.chdir('/nonexistent/path') except FileNotFoundError: print("The directory does not exist.")
- If the directory does not exist,
- Cross-Platform Compatibility:
- Use the
os.path
module for handling paths in a cross-platform way. For example:import os new_path = os.path.join(os.getcwd(), 'subfolder') os.chdir(new_path)
- Use the
Using pathlib
for Modern Path Management
Python’s pathlib
module (introduced in Python 3.4) provides a more intuitive way to manage file paths.
Example
from pathlib import Path
# Set the working directory
new_dir = Path('/path/to/directory')
Path.cwd() # Get current working directory
Path(new_dir).absolute() # Resolve to absolute path
# Change the directory
os.chdir(new_dir)