Extract file name from path, no matter what the os/path format
You can use the os.path.basename()
function to extract the file name from a file path, regardless of the operating system or path format.
Here is an example code snippet:
import os
path = '/path/to/myfile.txt'
filename = os.path.basename(path)
print(filename)
# Output: myfile.txt
Watch a video course
Python - The Practical Guide
You can also use the os.path.split()
function to split the path into a tuple of (head, tail) where tail is the last pathname component and head is everything leading up to that.
import os
path = '/path/to/myfile.txt'
head, tail = os.path.split(path)
print(tail)
# Output: myfile.txt
You can also use pathlib
library
from pathlib import Path
path = '/path/to/myfile.txt'
p = Path(path)
print(p.name)
# Output: myfile.txt
You can also use ntpath
library
import ntpath
path = '/path/to/myfile.txt'
print(ntpath.basename(path))
# Output: myfile.txt