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.
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:
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 chdir function.
os.chdir('..')
To move two directories up, use this code:
os.chdir('../')
Now, it’s time to modify our code.
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 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.