Hey guys, in this blog we will see a Python Program to Get the File Name From the File Path.
Example 1: Using the os module
import os # file name with extension file_name = os.path.basename('/root/file.ext') # file name without extension print(os.path.splitext(file_name)[0])
Output
file
- Here we have used os.path.splitext(file_name)[0] to extract the file name from the path.
- We did the same for extracting the extension where we took the [1] element.
Example 2: Using the Path module
from pathlib import Path print(Path('/root/file.ext').stem)
Output
file
- Here we have used Path().stem method to extract the file name.
- Stem is the final path component, without its suffix.
Check out our other python programming examples…