Get and Change the Current Working Directory in Python

In order to use the current working directory in Python, we are going to use the os module.

There is a method called getcwd() which stands for getting the current working directory and returns an absolute path.

Get the current working directory

This is very easy. First, import the os module and then print the path.

This is the result in my case.

C:\Users\Tom\PycharmProjects\algo\ppp

Change the current working directory

To change the directory, you have to use the chdir (change directory) of the os module.

The last result was:

C:\Users\Tom\PycharmProjects\algo\ppp

Let’s move one and two directories up to get these results.

C:\Users\Tom\PycharmProjects\algo\
C:\Users\Tom\PycharmProjects\

Normally, you can achieve this by using absolute paths, like:

But there is a more elegant way to do this.

To move one directory up, you can use two dots in the chdir function.

To move two directories up, use this code:

Now, it’s time to modify our code.

It returns the same result as last time, but this time it’s cleaner and we don’t have to know the working directory path to do it.

You can use the absolute path to change directories, if you want to change the path to a completely different one, in a different directory tree.