Table of Contents
In this example, you will learn to extract extension from the file name.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using splitext() method from os module
import os
file_details = os.path.splitext('/path/file.ext')
print(file_details)
print(file_details[1])
Output
('/path/file', '.ext')
.ext
os.path.splitext() gives a tuple with one item as the name of the file along with the path and the other is the extension of the file. If you want the file extension only, you can print it as shown above file_details[1].
2. Example 2: Using pathlib module
import pathlib
print(pathlib.Path('/path/file.ext').suffix)
Output
.ext
Using suffix attribute from pathlib module, we can get the extension of a file. In the above example, .ext is the extension of file file.ext.
Note: It works for python 3.4 and above.
Related posts:
Python print()
Python Program to Find Numbers Divisible by Another Number
Python Program to Sort a Dictionary by Value
Python timestamp to datetime and vice-versa
Python Program to Represent enum
Python String rjust()
Python input()
Python Program to Get the File Name From the File Path
Python Program to Parse a String to a Float or Int
Python del Statement
Python Tuple
Python Statement, Indentation and Comments
Python Namespace and Scope
Python String islower()
Python String startswith()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python complex()
Python Program to Find ASCII Value of Character
Python Tuple count()
Python Variables, Constants and Literals
Python Set add()
Python Tuple index()
Python String find()
Python Program to Remove Duplicate Element From a List
Python filter()
Python Generators
Python Program to Check Armstrong Number
Python String title()
Python set()
Python List
Python String maketrans()
Debug a JavaMail Program