I want to get the path of the current directory under which a .py file is executed.
For example a simple file D: est.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: est.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?
os.path.dirname(__file__) returns empty basename: Questions
What is the difference between os.path.basename() and os.path.dirname()?
1 answers
What is the difference between os.path.basename()
and os.path.dirname()
?
I already searched for answers and read some links, but didn"t understand. Can anyone give a simple explanation?
Answer #1
Both functions use the os.path.split(path)
function to split the pathname path
into a pair; (head, tail)
.
The os.path.dirname(path)
function returns the head of the path.
E.g.: The dirname of "/foo/bar/item"
is "/foo/bar"
.
The os.path.basename(path)
function returns the tail of the path.
E.g.: The basename of "/foo/bar/item"
returns "item"
From: http://docs.python.org/3/library/os.path.html#os.path.basename