os.path.dirname(__file__) returns empty

Python

Python Problem Overview


I want to get the path of the current directory under which a .py file is executed.

For example a simple file D:\test.py with code:

import os

print os.getcwd()
print os.path.basename(__file__)
print os.path.abspath(__file__)
print os.path.dirname(__file__)

It is weird that the output is:

D:\
test.py
D:\test.py
EMPTY

I am expecting the same results from the getcwd() and path.dirname().

Given os.path.abspath = os.path.dirname + os.path.basename, why

os.path.dirname(__file__)

returns empty?

Python Solutions


Solution 1 - Python

Because os.path.abspath = os.path.dirname + os.path.basename does not hold. we rather have

os.path.dirname(filename) + os.path.basename(filename) == filename

Both dirname() and basename() only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.

To get the dirname of the absolute path, use

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

Solution 2 - Python

import os.path

dirname = os.path.dirname(__file__) or '.'

Solution 3 - Python

can be used also like that:

dirname(dirname(abspath(__file__)))

Solution 4 - Python

os.path.split(os.path.realpath(__file__))[0]

os.path.realpath(__file__) return the abspath of the current script; os.path.split(abspath)[0] return the current dir

Solution 5 - Python

print(os.path.join(os.path.dirname(__file__))) 

You can also use this way

Solution 6 - Python

Since Python 3.4, you can use pathlib to get the current directory:

from pathlib import Path

# get parent directory
curr_dir = Path(__file__).parent

file_path = curr_dir.joinpath('otherfile.txt')

Solution 7 - Python

I guess this is a straight forward code without the os module..

__file__.split(__file__.split("/")[-1])[0]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlakeView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonDeveView Answer on Stackoverflow
Solution 3 - Pythonadnan dogarView Answer on Stackoverflow
Solution 4 - PythonRY_ ZhengView Answer on Stackoverflow
Solution 5 - PythonMikhailView Answer on Stackoverflow
Solution 6 - PythonMelleView Answer on Stackoverflow
Solution 7 - PythonMohammadArikView Answer on Stackoverflow