Get Directory of a File in Python

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:

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.

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.

This code will return a path of the current file directory.

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