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 help()
Python issubclass()
Python map()
Python Program to Find the Sum of Natural Numbers
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Get the Full Path of the Current Working Directory
Python Program to Make a Simple Calculator
Python Set symmetric_difference_update()
Python Program to Catch Multiple Exceptions in One Line
Python Program to Create a Long Multiline String
Python String istitle()
Python Program to Capitalize the First Character of a String
Python Program to Check If a List is Empty
Python Program to Find the Factorial of a Number
Python Program to Check Prime Number
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String title()
Python Data Structures and Algorithms - Benjamin Baka
Python Dictionary copy()
Python List pop()
Python Program to Extract Extension From the File Name
Python String capitalize()
Python Program to Convert Kilometers to Miles
Python String isupper()
Python Program to Display Fibonacci Sequence Using Recursion
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Program to Find Armstrong Number in an Interval
Python Program to Solve Quadratic Equation
Python *args and **kwargs