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 str()
Python Program to Copy a File
Python setattr()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Set union()
Python Program to Sort Words in Alphabetic Order
Python Program to Print Colored Text to the Terminal
Python List pop()
Python Set symmetric_difference_update()
Python Program to Print all Prime Numbers in an Interval
Python Operators
Python List copy()
Python Program to Count the Number of Occurrence of a Character in String
Python Program to Display Fibonacci Sequence Using Recursion
Python *args and **kwargs
Python iter()
Python Program to Concatenate Two Lists
Deep Learning in Python - LazyProgrammer
Python Sets
Python Program to Get File Creation and Modification Date
Python pow()
Python Decorators
Python super()
Python Set update()
Python Input, Output and Import
Python timestamp to datetime and vice-versa
Python String isprintable()
Python map()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Anonymous / Lambda Function
Python String rindex()
Python Program to Convert Kilometers to Miles