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?
This question is related to
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
can be used also like that:
dirname(dirname(abspath(__file__)))
import os.path
dirname = os.path.dirname(__file__) or '.'
print(os.path.join(os.path.dirname(__file__)))
You can also use this way
Source: Stackoverflow.com