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 compile()
Python Program to Capitalize the First Character of a String
Python Generators
Python pow()
Python Program to Check If a List is Empty
Python Set union()
Python String isalnum()
APIs in Node.js vs Python - A Comparison
Python Statement, Indentation and Comments
Python String isupper()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Find the Size (Resolution) of a Image
Python Variables, Constants and Literals
Python String splitlines()
Python ascii()
Python Program to Find Numbers Divisible by Another Number
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Find ASCII Value of Character
Python Program to Return Multiple Values From a Function
Python String count()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Calculate the Area of a Triangle
Python tuple()
Python sleep()
Python sorted()
Python Dictionary items()
Python Exception Handling Using try, except and finally statement
Python filter()
Python String rsplit()
Python Program to Convert Celsius To Fahrenheit
Python Shallow Copy and Deep Copy
Python String split()