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 complex()
Python List count()
Python Set issuperset()
Python String upper()
Python @property decorator
Python Set pop()
Python Program to Solve Quadratic Equation
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Merge Mails
Python pow()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python eval()
Python callable()
Python Set union()
Python Program to Check Leap Year
Python String startswith()
Python sorted()
Python Set symmetric_difference()
Python delattr()
Python Machine Learning - Sebastian Raschka
Python __import__()
Python Generators
Python memoryview()
Python filter()
Python id()
Python Program to Measure the Elapsed Time in Python
Python int()
Python next()
Python String isdecimal()
Python classmethod()
Python String ljust()
Python Multiple Inheritance