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!

import os

# Get the current working directory

current_directory = os.getcwd()

print(“Your current working directory is %s” % current_directory)

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/image1-53.png" data-lazy- height="640" src="data:image/svg xml,” width=”1365″>

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.

import os

# 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!

# let’s set a new working directory

new_working_directory = “https://linuxhint.com/home/kalyani/Desktop/PythonDirectory”

On Windows, you need to use double backslashes to define the directory.

#new_working_directory = “C:\Users\never\Desktop\PythonDirectory”

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!

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.”)

The full code would look like this:

import os

# 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 = “https://linuxhint.com/home/kalyani/Desktop/PythonDirectory”

new_working_directory = r“C:UsersneverDesktopPythonDirectory”

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:

new_working_directory = “C:\Users\never\Desktop\PythonDirectory\text.txt”

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:

new_working_directory = “C:UsersneverDesktopPythonDirectory”

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:

new_working_directory = “C:UsersneverDesktopPythonDirectory”

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.

new_working_directory = r“C:UsersneverDesktopPythonDirectory”

Method 2: We use double backslashes.

new_working_directory = “C:\Users\never\Desktop\PythonDirectory”

Method 3: We use a single forward slash.

new_working_directory = “C:/Users/never/Desktop/PythonDirectory”

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):

pip install path

(https://pypi.org/project/path/)

Next, we write:

from path import Path

import os

First, let’s check the current working directory using the os module and the getcwd() method.

# let’s check the current working directory

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:

# set the path to the new working directory

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.

# change the working directory

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!

# Re-check the working directory

# has it been changed?

cwd = os.getcwd()

print(“The new working directory is %s “ % cwd)

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/image2-54.png" data-lazy- height="726" src="data:image/svg xml,” width=”1368″>

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!

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/k-150×150.png612e42192197b.jpg" height="112" src="data:image/svg xml,” width=”112″>

Kalyani Rajalingham

I’m a linux and code lover.