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 dict()
Python Program to Merge Two Dictionaries
Python Program to Count the Number of Digits Present In a Number
Python Program to Count the Occurrence of an Item in a List
Intelligent Projects Using Python - Santanu Pattanayak
Python Program to Generate a Random Number
Python Program to Check Leap Year
Python Program to Check if a Number is Odd or Even
Python Set symmetric_difference_update()
Python String translate()
Python Program to Check Armstrong Number
Python List index()
Python pow()
Python String isprintable()
Python List Comprehension
Python Program to Delete an Element From a Dictionary
Python repr()
Python frozenset()
Python Program to Calculate the Area of a Triangle
Python Program to Print Hello world!
Python Dictionary get()
Python iter()
Python Program to Copy a File
Python eval()
Python Program to Shuffle Deck of Cards
Python Set remove()
Python sleep()
Python List insert()
Python Program to Access Index of a List Using for Loop
Python Program to Find HCF or GCD
Python Program to Convert Kilometers to Miles
Python List count()