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 Find All File with .txt Extension Present Inside a Directory
Python Program to Print Colored Text to the Terminal
Python Set intersection_update()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python getattr()
Python slice()
Python String capitalize()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Global, Local and Nonlocal variables
Python Program to Delete an Element From a Dictionary
Python bytearray()
Python Program to Find the Largest Among Three Numbers
Python Program to Generate a Random Number
Python map()
Python len()
Python Program to Count the Number of Occurrence of a Character in String
Python String find()
Python Objects and Classes
Python float()
Python List index()
Python String count()
Introduction to Scientific Programming with Python - Joakim Sundnes
Python String strip()
Python Dictionary items()
Python List append()
Python open()
Python Set intersection()
Python staticmethod()
Python Program to Check Leap Year
Python Dictionary update()
Python issubclass()
Python datetime