Skip to content
Advertisement

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

>>> 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?

Advertisement

Answer

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

os.path.basename(os.path.normpath("../dir/"))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement