In this example, you see how to get the directory+filename or directory+subdirectory from any given path in Python.

Get the file name and directory from a path in Python.

To extract the directory and file name in Python, use the os module. The os module has functions basename and dirname. Here is an example on how to use them:

import os

print(os.path.basename("/a/b/c/d"))       # d
print(os.path.basename("/a/b/c/d.txt"))   # d.txt
print(os.path.dirname("/a/b/c/d"))        # /a/b/c
print(os.path.dirname("/a/b/c/d.txt"))    # /a/b/c

print(os.path.basename("/a/b/c/d/"))      # Empty str
print(os.path.dirname("/a/b/c/d/"))       # /a/b/c/d

Output:

d
d.txt
/a/b/c
/a/b/c

/a/b/c/d

Trailing slash

A path that ends with a trailing slash is split at the last slash wich causes the last part to be an empty string.

Written by Loek van den Ouweland on 2020-08-05.
Questions regarding this artice? You can send them to the address below.