>>> os.path.basename("../dir/")
''
$ basename ../dir/
dir
documentation
os.path.basename(path)
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function
split()
. Note that the result of this function is different from the Unix basename program; where basename for'/foo/bar/'
returns'bar'
, thebasename()
function returns an empty string (''
).
Is there a function that isn't different from Unix basename?
basename() function takes an argument of a specified path and returns the base name of the pathname path. To extract the file name from the path in Python, use the os. path. basename() method.
path module is a very extensively used module that is handy when processing files from different places in the system. It is used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters.
The path is split with " / " as a seperator, sliced to remove the last item in the list, in OPs case "myFile. txt", and joined back with " / " as a seperator. This will give the path with the file name removed.
Not in one function, AFAIK, but it is not difficult. Just remove the trailing slash first:
os.path.basename(os.path.normpath("../dir/"))
Looks like pathlib.Path
's name attribute is what you want.
from pathlib import Path
pa = Path('/foo/bar/zoom')
print(f"{pa.name=}")
pa = Path('/foo/bar/')
print(f"{pa.name=}")
Output (to which I've added the macOS basename
):
(venv38) me@explore$ python test.py
pa.name='zoom'
pa.name='bar'
(venv38) me@explore$ basename '/foo/bar/zoom'
zoom
(venv38) me@explore$ basename /foo/bar/
bar
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