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 current working directory

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

This is the result in my case.

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:

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

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 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 now 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 the different directory tree.