Python Program to Get the File Name From the File Path – 2024

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

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 514

Leave a Reply

Your email address will not be published. Required fields are marked *