How do I get the full path of the current file's directory? How do I get the full path of the current file's directory? python python

How do I get the full path of the current file's directory?


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 pathlibpathlib.Path(__file__).parent.resolve()

For the current working directory:

import pathlibpathlib.Path().resolve()

Python 2 and 3

For the directory of the script being run:

import osos.path.dirname(os.path.abspath(__file__))

If you mean the current working directory:

import osos.path.abspath(os.getcwd())

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.

References

  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?


Using Path is the recommended way since Python 3:

from pathlib import Pathprint("File      Path:", Path(__file__).absolute())print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__  

Documentation: pathlib

Note: If using Jupyter Notebook, __file__ doesn't return expected value, so Path().absolute() has to be used.


In Python 3.x I do:

from pathlib import Pathpath = Path(__file__).parent.absolute()

Explanation:

  • Path(__file__) is the path to the current file.
  • .parent gives you the directory the file is in.
  • .absolute() gives you the full absolute path to it.

Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).