How To Change The Directory In Python

Changing the directory in Python is an essential skill when working with files and directories. Being able to navigate file systems can help you create, read, and write files more efficiently. In this tutorial, we will learn how to change the working directory in Python using the os module.

Step 1: Import the os module

The os module in Python provides a way to interact with the operating system. It includes various functions to work with files and directories. To change the directory, we first need to import the os module.

Step 2: Check the current working directory

Before changing the working directory, it is essential to know the current directory. The os.getcwd() function helps to find the current working directory. The output will be the directory path.

Current working directory: /home/myproject

Step 3: Change the working directory

To change the working directory, we’ll use the os.chdir() function. Pass the desired directory path as a string argument. If the given path does not exist, a FileNotFoundError will be raised.

Step 4: Verify if the directory has changed

Now let’s confirm if our working directory has changed. We’ll use the os.getcwd() function again to verify the new path.

New working directory: /home/myproject/new_directory

Note that the working directory will be relative to the directory from which you run the script. Use absolute paths to avoid confusion.

Full code:

Output:

Current working directory: /home/myproject
New working directory: /home/myproject/new_directory

Conclusion

In this tutorial, we learned how to change the current working directory in Python using the os module. Understanding how to navigate directories is crucial when working with files and directories in your Python projects.