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 isinstance()
Python List count()
Python Dictionary clear()
Python List index()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python String find()
Python sum()
Python Dictionary values()
Python Set difference()
Python String expandtabs()
Python String splitlines()
Python staticmethod()
Python compile()
Node.js vs Python for Backend Development
Python Set intersection()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program Read a File Line by Line Into a List
Python hash()
Python Tuple count()
Python Global Keyword
Python Program to Find the Size (Resolution) of a Image
Python Program to Concatenate Two Lists
Python List pop()
Python Dictionary popitem()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Sort Words in Alphabetic Order
Python callable()
Python Type Conversion and Type Casting
Python Program to Extract Extension From the File Name
Python Program to Create Pyramid Patterns
Python String upper()
Python Data Structures and Algorithms - Benjamin Baka