Table of Contents
In this example, you will learn to get the file name from the file path.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using 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
basename()
gives the name of the last file/folder of the path, whereas splitext()
splits the file name into filename and extension.
import os print(os.path.splitext(file_name))
Output
('file', '.ext')
2. Example 2: Using Path module
from pathlib import Path print(Path('/root/file.ext').stem)
Output
file
Using stem
attribute of Path
module, the file name can be extracted as shown above.
It works for python 3.4 and above.
Related posts:
Python Program to Parse a String to a Float or Int
Python String zfill()
Python input()
Python Program to Iterate Over Dictionaries Using for Loop
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python bin()
Python String format()
Python super()
Python String endswith()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Measure the Elapsed Time in Python
How to get current date and time in Python?
Python locals()
Python Multiple Inheritance
Python Set issubset()
Node.js vs Python for Backend Development
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Randomly Select an Element From the List
Python String isnumeric()
Deep Learning with Python - Francois Cholletf
Python Program to Find LCM
Python Program to Differentiate Between del, remove, and pop on a List
Python String isdigit()
Python ord()
Python bytes()
Python for Loop
Python Program to Count the Number of Occurrence of a Character in String
Python filter()
Python Program to Convert String to Datetime
Python type()
Python hex()