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 Multiple Inheritance
Python Program to Check if a Number is Odd or Even
Python open()
Python frozenset()
Python Program to Extract Extension From the File Name
Python super()
Python any()
Machine Learning with Python for everyone - Mark E.Fenner
Python Program to Transpose a Matrix
Python List reverse()
Python Dictionary keys()
Python Recursion
Python strptime()
Python List
Python Program to Print Colored Text to the Terminal
Python Program to Print Hello world!
Python callable()
Python Program to Count the Number of Digits Present In a Number
Python Data Structures and Algorithms - Benjamin Baka
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
APIs in Node.js vs Python - A Comparison
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Copy a File
Python Program to Count the Number of Each Vowel
Python Set isdisjoint()
Python List clear()
Python ord()
Python break and continue
Python set()
Python Operator Overloading
Python eval()
Python Program to Find LCM