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:

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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__))

Method 2

import os.path

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

Method 3

can be used also like that:

dirname(dirname(abspath(__file__)))

Method 4

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

Method 5

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

You can also use this way

Method 6

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')

Method 7

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

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x