Python How To Get The Last Directory Name In A Path

Do you like this?

This short post shows you various ways to get the last directory's name in a path by Python


Suppose this is the path you want to extract:

path ="/test1/test2/test3/test.txt"

Method 1: os.path.basename

os.path.basename: Returns the final component of a pathname
print os.path.basename(path) # 'test.txt'
print os.path.dirname(path) # '/test1/test2/test3'
print os.path.basename(os.path.dirname(path)) # 'test3'

Method 2: os.path.split

os.path.split: Return tuple (head, tail) where tail is everything after the final slash.
print os.path.split(path) #('/test1/test2/test3', 'test.txt')
print os.path.dirname(path) # '/test1/test2/test3'
print os.path.split(os.path.dirname(path)) # ('/test1/test2', 'test3')
print os.path.split(os.path.dirname(path))[1] # 'test3'

comments powered by Disqus