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.
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:
Extract the file name from a file path, regardless of the operating system or path format in Python
import os
path = '/path/to/myfile.txt'
filename = os.path.basename(path)
print(filename)
# Output: myfile.txt
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
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.
Split the directory path into a tuple of (head, tail) in Python
import os
path = '/path/to/myfile.txt'
head, tail = os.path.split(path)
print(tail)
# Output: myfile.txtYou can also use pathlib library
Using pathlib to extract file name from path in Python
from pathlib import Path
path = '/path/to/myfile.txt'
p = Path(path)
print(p.name)
# Output: myfile.txtYou can also use ntpath library
Using ntpath to extract file name from path in Python
import ntpath
path = '/path/to/myfile.txt'
print(ntpath.basename(path))
# Output: myfile.txt