Python 3 – os.chdir() Method
The os.chdir()
method in Python is used to change the current working directory to the directory specified as the parameter of the method. The current working directory is the directory in which the Python script is being executed.
Syntax
The syntax of the os.chdir()
method is quite simple. It takes one mandatory parameter, which is the path of the directory to which we want to change the current working directory.
os.chdir(path)
Here, path
is the path of the directory to which we want to change the current working directory. This path can either be a relative path or an absolute path.
Examples
Let’s see some examples to get a better understanding of the os.chdir()
method.
Example 1: Changing the Working Directory to a Subdirectory
Suppose we have a directory called my_files
which contains a subdirectory called documents
. Now, in order to change the current working directory to this subdirectory, we can use the os.chdir()
method as follows:
import os
os.chdir("my_files/documents")
Here, we are changing the current working directory to the documents
subdirectory of the my_files
directory.
Example 2: Changing the Working Directory to the Parent Directory
Suppose we want to change the current working directory to the parent directory of the current directory. We can use the os.chdir()
method with the ..
notation to achieve this.
import os
os.chdir("..")
This will change the current working directory to the parent directory.
Example 3: Changing the Working Directory to an Absolute Path
Suppose we want to change the current working directory to an absolute path, say C:\my_files
. We can use the os.chdir()
method as follows:
import os
os.chdir("C:\\my_files")
Here, we are using a backslash (\
) as the directory separator, which is the convention on Windows systems.
Error Handling
The os.chdir()
method can raise a number of exceptions. Some of the common exceptions are:
FileNotFoundError
: If the specified directory does not exist.NotADirectoryError
: If the specified path is not a directory.
In order to handle these exceptions, we can use a try-except
block as follows:
import os
try:
os.chdir("non_existent_directory")
except FileNotFoundError:
print("Directory not found")
except NotADirectoryError:
print("Not a directory")
Conclusion
In this article, we learned about the os.chdir()
method in Python. We saw how to use this method to change the current working directory to a different directory. We also saw some examples and learned about error handling. The os.chdir()
method is a very useful tool that can help us manage the directory structure of our Python projects.