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 Read a File Line by Line Into a List
Python String endswith()
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Check if a Number is Positive, Negative or 0
Python String expandtabs()
Python pass statement
Python Program to Differentiate Between type() and isinstance()
Python Program to Compute the Power of a Number
Python Get Current time
Python String rfind()
Python Program to Convert Decimal to Binary Using Recursion
Python Package
Python Statement, Indentation and Comments
Python Set difference()
Python String isalnum()
Python dir()
Python Anonymous / Lambda Function
How to Get Started With Python?
Python List index()
Python strptime()
Python len()
Python Program to Find ASCII Value of Character
Python String partition()
Python Inheritance
Python Program to Check Whether a String is Palindrome or Not
Python Program to Display the multiplication Table
Python Program to Find the Sum of Natural Numbers
Python Program to Get the Class Name of an Instance
Python Program to Find Sum of Natural Numbers Using Recursion
Python set()
Python Generators
Python String title()