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.
|
1 |
import os |
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.
|
1 2 |
current_directory = os.getcwd() print("Current working directory:", current_directory) |
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.
|
1 2 |
new_directory = "/home/myproject/new_directory" os.chdir(new_directory) |
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.
|
1 2 |
current_directory = os.getcwd() print("New working directory:", current_directory) |
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:
|
1 2 3 4 5 6 7 8 9 10 |
import os current_directory = os.getcwd() print("Current working directory:", current_directory) new_directory = "/home/myproject/new_directory" os.chdir(new_directory) current_directory = os.getcwd() print("New working directory:", current_directory) |
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.