Python – How to get the full path of the current file’s directory


I want to get the current file's directory path.
I tried:

>>> os.path.abspath(__file__)

But how can I retrieve the directory's path?

For example:


Best Solution

The special variable __file__ contains the path to the current file. From that we can get the directory using either Pathlib or the os.path module.

Python 3

For the directory of the script being run:

import pathlib

For the current working directory:

import pathlib

Python 2 and 3

For the directory of the script being run:

import os

If you mean the current working directory:

import os

Note that before and after file is two underscores, not just one.

Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.


  1. pathlib in the python documentation.
  2. os.path - Python 2.7, os.path - Python 3
  3. os.getcwd - Python 2.7, os.getcwd - Python 3
  4. what does the __file__ variable mean/do?