Python os.chdir() method is used to change the current working directory to a provided path.
The current working directory is the folder in which the process operates, and it’s used as the default location for file and directory operations.
The os.chdir() function can accept both relative and absolute paths. If a relative path is given, it’s interpreted as relative to the current working directory.
While this method works across different operating systems, the format of the path (for example, forward vs. backward slashes) should be appropriate to the operating system.
Syntax
os.chdir(path)
Parameters
path: It is the complete path of a directory to be changed to a new directory path.
Return value
This method does not return any value.
Exception
This method may raise the following exceptions:
- OSError: This exception is raised when a system-related error occurs. If the specified path does not exist or the process lacks sufficient privileges to change the working directory, it raises this error.
- FileNotFoundError: This exception is raised when a directory is requested but does not exist.
- PermissionError: This occurs when accessing illegal memory or resources.
Example 1: Basic usage
import os
os.chdir("/Users/krunallathiya/Desktop/Code")
print("The directory has been changed")
Output
The directory has been changed
Example 2: Getting the current working directory
To get the current working directory, use the “os.getcwd()” method. It returns the location of the current working directory (cwd).
import os
print(os.getcwd())
os.chdir("/Users/krunallathiya/Desktop/code/pythonenv")
print("The directory has been changed to this: ")
print(os.getcwd())
Output
/Users/krunallathiya/Desktop/Code/R
The directory has been changed to this:
/Users/krunallathiya/Desktop/Code/pythonenv
Example 3: Handling the errors while changing the directory
Here are three different ways to handle these errors.
Method 1: Using the try and except blocks
import os
def change_directory(directory):
try:
os.chdir(directory)
except OSError as e:
print(e)
if __name__ == "__main__":
change_directory("/path/to/directory")
Method 2: Use the os.path.exists()
import os
def change_directory(directory):
if os.path.exists(directory):
os.chdir(directory)
else:
print("Directory does not exist.")
if __name__ == "__main__":
change_directory("/path/to/directory")
Method 3: Use the try and finally blocks
import os
def change_directory(directory):
cwd = os.getcwd()
try:
os.chdir(directory)
except OSError as e:
print(e)
finally:
os.chdir(cwd)
if __name__ == "__main__":
change_directory("/path/to/directory")
That’s it.