Appearance
How to set the current working directory?
You can set the current working directory in Python using the os module, specifically the chdir() function. It accepts both absolute and relative paths, though absolute paths are generally safer. Here is an example with basic error handling:
Current working directory in Python using the os module
python
import os
try:
# Set the current working directory to "/path/to/directory"
os.chdir("/path/to/directory")
except OSError as e:
print(f"Failed to change directory: {e}")
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
You can also use os.getcwd() to get the current working directory.
Get the current working directory using os module in Python
python
import os
# Get the current working directory
current_directory = os.getcwd()
print(current_directory)Note that the pathlib module does not provide a direct function to change the working directory. It is primarily used for path manipulation and resolution.
Retrieve the current working directory using pathlib in Python
python
from pathlib import Path
# Retrieve the current working directory as a Path object
current_path = Path.cwd()
print(current_path)Please note that the chdir() function only changes the current working directory for the current process, not for the entire system.