Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me c
:
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c
Best Answer
There's a function that returns exactly what you want
WARNING: When
os.path.basename()
is used on a POSIX system to get the base name from a Windows-styled path (e.g."C:\\my\\file.txt"
), the entire path will be returned.Example below from interactive python shell running on a Linux host: