This os.chdir()
method changes the current working directory to a specified path instance. It does not return any value.
This descriptor
path
must refer to the open directory, not to an open file.
The syntax is given below:
os.chdir(path)
path
: This is the string as a directory or a path value.
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.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}")
os.getcwd()
method to extract the current working directory.path
variable as a string.chdir(path)
method to change the current working directory.