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 Trim Whitespace From a String
Python oct()
Python String isdigit()
Python all()
Python List count()
Python Program to Check Prime Number
Python Set pop()
Python Program to Check Whether a String is Palindrome or Not
Python Set symmetric_difference()
Python Set isdisjoint()
Python String splitlines()
Python Program to Count the Number of Each Vowel
Python String isupper()
Python Program to Randomly Select an Element From the List
Python Program to Shuffle Deck of Cards
Python delattr()
Python Dictionary copy()
Python frozenset()
Python Objects and Classes
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Split a List Into Evenly Sized Chunks
Python String find()
Python String join()
Python tuple()
Python Program to Find the Largest Among Three Numbers
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Directory and Files Management
Python float()
How to get current date and time in Python?
Python Set union()
Python Program to Catch Multiple Exceptions in One Line
Python Object Oriented Programming