Coder Perfect

How do I get the entire path to the directory of the current file?

Problem

I’m looking for the directory path of the current file. I attempted:

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

But how can I get the path to the directory?

For example:

'C:\\python27\\'

Asked by Shubham

Solution #1

The path to the current file is stored in the special variable __file__. We can then use Pathlib or the os.path module to fetch the directory.

The following is the directory where the script is being run:

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

To get to the current working directory, type:

import pathlib
pathlib.Path().resolve()

The following is the directory where the script is being run:

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

If you’re referring to the current working directory, it’s as follows:

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

It’s worth noting that the underscores before and after the file are two, not one.

Also, because there is no concept of “current file” if you are running interactively or have loaded code from something other than a file (e.g., a database or an online resource), __file__ may not be set if you are running interactively or have loaded code from something other than a file (e.g., a database or an online resource). The above response assumes that you’re running a python script from a file, which is the most frequent circumstance.

Answered by Bryan Oakley

Solution #2

Since Python 3, using Path is the recommended method:

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

Documentation: pathlib

Note: If you’re using Jupyter Notebook, __file__ doesn’t provide the expected value, so you’ll need to use Path instead (). It’s necessary to utilize absolute().

Answered by Ron Kalian

Solution #3

I perform the following in Python 3.x:

from pathlib import Path

path = Path(__file__).parent.absolute()

Explanation:

The contemporary way to work with paths is to use pathlib. If you want to use it as a string later, just do str (path).

Answered by Arminius

Solution #4

Try this:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))

Answered by Akshaya Natarajan

Solution #5

import os
print os.path.dirname(__file__)

Answered by chefsmart

Post is based on https://stackoverflow.com/questions/3430372/how-do-i-get-the-full-path-of-the-current-files-directory