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
A path that ends with a trailing slash is split at the last slash wich causes the last part to be an empty string.