os.path.dirname(__file__) returns empty


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:


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

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


returns empty?

Asked By: Flake



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

Answered By: Sven Marnach

You can also use this way

Answered By: Mikhail
import os.path

dirname = os.path.dirname(__file__) or '.'
Answered By: Deve

can be used also like that:

Answered By: adnan dogar

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

Answered By: RY_ Zheng

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

Answered By: MohammadArik

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')
Answered By: Melle
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.