What is the os.chdir() method in Python?
This os.chdir() method changes the current working directory to a specified path instance. It does not return any value.
This descriptor
pathmust refer to the open directory, not to an open file.
Syntax
The syntax is given below:
os.chdir(path)
Parameters
path: This is the string as a directory or a path value.
Exception
The chdir() method may raise the following exceptions:
OSError: This exception is raised when a system-related error occurs.FileNotFoundError: This exception is raised when a directory is requested but does not exist.PermissionError: This occurs when accessing illegal memory or resources.
Explanation
Let’s discuss this method in detail:
# Demo codeimport os# Get current working directorydirctory = os.getcwd()print(f"Current directory: Before= {dirctory}")# Path to chnagepath = '/usr/'# Change current working directoryos.chdir(path)# Get current working directory againdirctory = os.getcwd()print(f"Current working directory: After= {dirctory}")
- Line 4 : We use the
os.getcwd()method to extract the current working directory. - Line 7 : We see a temporary directory in the
pathvariable as a string. - Line 9 : We use the
chdir(path)method to change the current working directory. - Line 11: We again extract the current working dir to ensure change.