A working directory is a current directory in which we are working and from which the script is run; within this directory, we have access to many files (the ones located within it). However, we sometimes need to change directories and go back and forth between files and folders. In this tutorial, we will learn how to change the working directory in Python.
OS MODULE
In the first place, to achieve this, we will need the os module in Python. Since it comes pre-installed, there is no need to install anything. The OS module is typically used in Python to interact, manage and modify files and folders on the system. For example, we can create/remove directories, change working directories, walkthrough files, check whether files exist, etc.… Needless to say that it is a very useful module.
Getting the current working directory
To get the current working directory, we use the getcwd() method from the os module. Please note here that no argument is passed. In my case, the output was “/home/kalyani/PycharmProjects/pythonProject1” on an Ubuntu machine (running PyCharm). This means that the main script – main.py – is located within this folder (pythonProject1). And mind you, the working directory, first and foremost a folder!
# Get the current working directory
current_directory = os.getcwd()
print("Your current working directory is %s" % current_directory)
Changing the current working directory
Changing your working directory is easy with the chdir() method, which takes exactly one argument – the path to the new location as a string.
# Get the current working directory
current_directory = os.getcwd()
print("Your current working directory is %s" % current_directory)
The first thing to do is to set the new path to the working directory. On Ubuntu, this is very straightforward!
new_working_directory = "/home/kalyani/Desktop/PythonDirectory"
On Windows, you need to use double backslashes to define the directory.
Next, we define a try-except clause. If the path exists, we will use the chdir() method to change the working directory to a new working directory. If the path is not a directory, it will throw an error!
os.chdir(new_working_directory)
print("The working directory has been changed!")
print("WD: %s " % os.getcwd())
except NotADirectoryError:
print("You have not chosen a directory.")
except FileNotFoundError:
print("The folder was not found. The path is incorrect.")
except PermissionError:
print("You do not have access to this folder/file.")
The full code would look like this:
# Get the current working directory
current_directory = os.getcwd()
print("Your current working directory is %s" % current_directory)
# let's set a new working directory
#new_working_directory = "/home/kalyani/Desktop/PythonDirectory"
new_working_directory = r"C:\Users\never\Desktop\PythonDirectory"
try:
os.chdir(new_working_directory)
print("The working directory has been changed!")
print("WD: %s " % os.getcwd())
except NotADirectoryError:
print("You have not chosen a directory.")
except FileNotFoundError:
print("The folder was not found. The path is incorrect.")
except PermissionError:
print("You do not have access to this folder/file.")
In fact, mistakes might raise various types of exceptions:
i. NotADirectoryError:
Now suppose for an instance that I wrote the following code for the path or the new working directory:
What you can note here is that I’m pointing the path to a text document called text.txt. And the latter will throw an error known as a NotADirectoryError. In other words, your path must point to a directory of some sort.
ii. FileNotFoundError:
A FileNotFoundError is thrown when the path does not exist. So, suppose for the moment that I do not have a directory by the name of PythonDirectory on my Desktop and that I set my path to:
It will throw a FileNotFoundError. This error simply means that the directory we’re pointing to doesn’t exist or wasn’t found.
iii. PermissionError:
A PermissionError is raised when the user doesn’t have adequate permissions to modify or access the chosen directory.
iv. SyntaxError:
A syntax error occurs when there’s a syntax error in the path. On Windows, if we write to say:
A synthax error is thrown! However, a syntax error is much harder to catch as it needs to be evaluated, imported, or executed. As such, when we write try-except blocks, it’s harder to catch such an error.
On Windows, to avoid any errors, the path can be written out in one of three different ways such that no errors are thrown:
Method 1: In this method, we add an “r” before setting out the string.
Method 2: We use double backslashes.
Method 3: We use a single forward slash.
PATH MODULE
We can also change the working directory using the path module. First, install the path as follows (I’ve also given the link to the module):
(https://pypi.org/project/path/)
Next, we write:
import os
First, let’s check the current working directory using the os module and the getcwd() method.
cwd = os.getcwd()
print("The current working directory is: %s " % cwd)
print("---------------------------------------------")
Next, set the path to the new working directory. In this case, I have chosen to set the example on a Windows machine:
new_path = "C:\\Users\\never\\Desktop\\PythonDirectory"
Use Path() to change the working directory. Path() takes only one argument here: the actual path to the new working directory and uses the chdir() method to accomplish the task.
Path(new_path).chdir()
Re-check if the working directory has been changed. And here, as you can see in the picture, the working directory has indeed been changed!
# has it been changed?
cwd = os.getcwd()
print("The new working directory is %s " % cwd)
Changing working directories is an easy task and takes but one method – the chdir(path) method. However, depending on whether you’re on a Windows machine or a Linux machine, you have to be careful about how you input the path as a string. If incorrectly inputted, it can throw an error!
Happy Coding!