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


Question

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

>>> os.path.abspath(__file__)
'C:\\python27\\test.py'

But how can I retrieve the directory's path?

For example:

'C:\\python27\\'
1
632
8/1/2019 6:26:31 AM

Accepted Answer

If you mean the directory of the script being run:

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

If you mean the current working directory:

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

1314
1/3/2019 10:42:43 PM

Using Path is the recommended way since Python 3:

from pathlib import Path
print("File      Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute())  

Documentation: pathlib

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon