If you want to get the current directory of a script being executed you can’t use the code to find the current working directory.
What you have to do, is to find a part of the current file, not a working directory.
Let’s take a look at the following example.
The full path to our script test.py is:
C:\Users\Tom\PycharmProjects\algo\temp
But if I run the following command:
1 2 3 4 |
import os current_dir = os.getcwd() print(current_dir) |
I’m going to get a different path:
C:\Users\Tom\PycharmProjects\algo\ppp
That’s why the working directory is not always the directory where the executed file is located.
I’ll show you two ways you can access the path to the current file.
Get the absolute path of a file
The quickest way to get the directory of the current file is to use a special variable called __file__ and pass it as an argument to the realpath method of the os.path function.
1 2 3 4 |
import os real_path = os.path.realpath(__file__) print(real_path) |
This code returns an absolute path to the current file.
C:\Users\Tom\PycharmProjects\algo\temp\test.py
Get the path of the file directory
Now, what we have to do, is to get the directory of the current path. You can do it by running this code.
1 2 3 4 5 6 |
import os real_path = os.path.realpath(__file__) dir_path = os.path.dirname(real_path) print(dir_path) |
This code will return a path of the current file directory.
C:\Users\Tom\PycharmProjects\algo\temp