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:
Deep Learning in Python - LazyProgrammer
Python List extend()
Intelligent Projects Using Python - Santanu Pattanayak
Python Program to Illustrate Different Set Operations
Python Objects and Classes
Python String casefold()
Python String swapcase()
Python Function Arguments
Python Get Current time
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Display Calendar
Python Program to Find the Size (Resolution) of a Image
Python List copy()
Python Program to Print Colored Text to the Terminal
Python Namespace and Scope
Python Set intersection_update()
Python Program to Find the Square Root
Python String rindex()
Python String endswith()
Python Program to Display the multiplication Table
Python property()
Python Program to Access Index of a List Using for Loop
Python enumerate()
Python globals()
Python int()
Python RegEx
Python Dictionary fromkeys()
Python Program to Check If a String Is a Number (Float)
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Program to Check if a Key is Already Present in a Dictionary
Python List reverse()
Python Program to Catch Multiple Exceptions in One Line