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 Set union()
Python format()
Python Program to Copy a File
Python String format_map()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Split a List Into Evenly Sized Chunks
Python String index()
Python String rstrip()
How to Get Started With Python?
Python Program to Return Multiple Values From a Function
Python Package
Python Program to Find the Largest Among Three Numbers
Python Objects and Classes
Python min()
Python Program to Find HCF or GCD
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Trim Whitespace From a String
Python Program to Print all Prime Numbers in an Interval
Python Program to Check If a List is Empty
Intelligent Projects Using Python - Santanu Pattanayak
Python List append()
Python List remove()
Python round()
Python Program to Differentiate Between type() and isinstance()
Python sorted()
Python Operator Overloading
Python String encode()
APIs in Node.js vs Python - A Comparison
Deep Learning with Python - Francois Chollet
Python filter()
Python String isalnum()
Python while Loop