The os. path. basename(path) function returns the tail of the path in Python. These functions are used when you get the filename/directory name given a full pathname.
path. dirname() method in Python is used to get the directory name from the specified path.
Using os. path. join makes it obvious to other people reading your code that you are working with filepaths. People can quickly scan through the code and discover it's a filepath intrinsically.
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
To summarize what was mentioned by Breno above
Say you have a variable with a path to a file
path = '/home/User/Desktop/myfile.py'
os.path.basename(path)
returns the string 'myfile.py'
and
os.path.dirname(path)
returns the string '/home/User/Desktop'
(without a trailing slash '/')
These functions are used when you have to get the filename/directory name given a full path name.
In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py'
you just have myfile.py
), os.path.dirname(path)
returns an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With