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 Count the Occurrence of an Item in a List
Python Set intersection()
Python Program to Create a Long Multiline String
Deep Learning with Python - Francois Cholletf
Python pass statement
Python List extend()
Python String upper()
Python List index()
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Check Armstrong Number
Python List append()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Sort a Dictionary by Value
Python Set discard()
Python frozenset()
Python repr()
Python time Module
Python Set issubset()
Python Program to Capitalize the First Character of a String
Python Program to Find Factorial of Number Using Recursion
Python Program to Get File Creation and Modification Date
Python Program to Convert Decimal to Binary Using Recursion
Python Set clear()
Python Program to Create a Countdown Timer
Python List Comprehension
Python Program to Find the Square Root
Python classmethod()
Introduction to Scientific Programming with Python - Joakim Sundnes
How to Get Started With Python?
Python Tuple index()
Python divmod()
Python Set issuperset()