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 Program to Remove Punctuations From a String
Python Machine Learning Eqution Reference - Sebastian Raschka
Python int()
Python Program to Count the Occurrence of an Item in a List
Python Exception Handling Using try, except and finally statement
How to get current date and time in Python?
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python str()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python String lstrip()
Python List remove()
Python Dictionary get()
Python Program to Transpose a Matrix
Python Program to Solve Quadratic Equation
Python Program to Create a Countdown Timer
Python Program to Find the Largest Among Three Numbers
Deep Learning in Python - LazyProgrammer
Python Program to Get Line Count of a File
Python Program to Find the Size (Resolution) of a Image
Python Set issuperset()
Python String zfill()
Python bytearray()
Python Program to Merge Two Dictionaries
Python Dictionary values()
Python callable()
Python String isdigit()
Python Program to Display the multiplication Table
Python divmod()
Python List clear()
Python Program to Illustrate Different Set Operations
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Sort Words in Alphabetic Order