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.
1 2 3 4 |
import os cwd = os.getcwd() print(cwd) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
import os cwd = os.getcwd() print(cwd) os.chdir('C:\\Users\\Tom\\PycharmProjects\\algo\\') cwd = os.getcwd() print(cwd) os.chdir('C:\\Users\\Tom\\PycharmProjects\\') cwd = os.getcwd() print(cwd) |
But there is a more elegant way to do this.
To move one directory up, you can use two dots in the chdir function.
1 |
os.chdir('..') |
To move two directories up, use this code:
1 |
os.chdir('../') |
Now, it’s time to modify our code.
1 2 3 4 5 6 7 8 9 10 11 12 |
import os cwd = os.getcwd() print(cwd) os.chdir('..') cwd = os.getcwd() print(cwd) os.chdir('../') cwd = os.getcwd() print(cwd) |
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.