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 to 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:

But if I run the following command:

I’m going to get a different path:

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 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.

Get 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.