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 del Statement
Python dir()
Python Set add()
Python Set isdisjoint()
Python filter()
Python String rstrip()
Python String isprintable()
Python *args and **kwargs
Python Program to Add Two Matrices
Python Set intersection_update()
Python List remove()
Python Program to Delete an Element From a Dictionary
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Compute all the Permutation of the String
Python max()
Python map()
Python for Loop
Python Program to Display Fibonacci Sequence Using Recursion
Python Set difference_update()
Python float()
Python Get Current time
Python String translate()
Python String endswith()
Python sleep()
Python Program to Print all Prime Numbers in an Interval
Python String lstrip()
Python Program to Find Hash of File
Python Program to Catch Multiple Exceptions in One Line
Python Closures
Python Multiple Inheritance
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python object()