0 votes
1 view
in Python by (16.1k 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 (107k 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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked 2 days ago in Python by laddulakshana (1.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...