Back
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
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
By importing, the ntpath library (which is equivalent to os.path when running on windows) will work for all paths on all platforms. And by using ntpath.split or ntpath.basename Windows paths can use either backslash or forward slash as path separator.
Following is the code that will give your desired output:-
import ntpathntpath.basename("a/b/c")def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head)abc= ['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'][path_leaf(path) for path in abc]
import ntpath
ntpath.basename("a/b/c")
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
abc= ['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']
[path_leaf(path) for path in abc]
Try using this:
import osprint(os.path.basename(your_path))
import os
print(os.path.basename(your_path))
For more information, refer to this link:
https://docs.python.org/2/library/os.path.html#os.path.basename
31k questions
32.8k answers
501 comments
693 users