Friday 29 July 2022

Get filename from linux or windows path

This is working for linux and windows as well with standard library

paths = ['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']

def path_leaf(path):
    return path.strip('/').strip('\\').split('/')[-1].split('\\')[-1]
 

[path_leaf(path) for path in paths] 


from: https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format