This advertisement helps me to keep writing articles on this website

Get the file name and directory from a path in Python

In this example, you see how to get the directory+filename or directory+subdirectory from any given 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 August 05, 2020. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.