Advertisement
Advertisement


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\\'
2019/08/01
1
854
8/1/2019 6:26:31 AM

Accepted Answer

Python 3

For the directory of the script being run:

import pathlib
pathlib.Path(__file__).parent.absolute()

For the current working directory:

import pathlib
pathlib.Path().absolute()

Python 2 and 3

For 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.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 2.7, os.path 3.8
  3. os.getcwd 2.7, os.getcwd 3.8
  4. what does the __file__ variable mean/do?
2020/01/11
1740
1/11/2020 3:46:57 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.

2019/07/24

In Python 3.x I do:

from pathlib import Path

path = 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).

2019/02/26

import os
print os.path.dirname(__file__)
2010/08/07

You can use os and os.path library easily as follows

import os
os.chdir(os.path.dirname(os.getcwd()))

os.path.dirname returns upper directory from current one. It lets us change to an upper level without passing any file argument and without knowing absolute path.

2017/04/02

Try this:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))
2019/05/23

Source: https://stackoverflow.com/questions/3430372
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]