Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (19k points)

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

2 Answers

0 votes
by (106k points)
  • 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 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]

0 votes
by (20.3k points)

Try using this:  

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...