Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have a basename function that is equal to Unix basename?

Tags:

python

>>> 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', the basename() function returns an empty string ('').

Is there a function that isn't different from Unix basename?

like image 736
Mike Avatar asked May 12 '21 01:05

Mike


People also ask

How do I get a Basename in Python?

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.

What is path in Python?

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.

How do I remove the last directory from a path in Python?

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.


2 Answers

Not in one function, AFAIK, but it is not difficult. Just remove the trailing slash first:

os.path.basename(os.path.normpath("../dir/"))
like image 85
Amadan Avatar answered Oct 27 '22 01:10

Amadan


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
like image 22
JL Peyret Avatar answered Oct 27 '22 01:10

JL Peyret