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 Set update()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python setattr()
Python String isidentifier()
Python Variables, Constants and Literals
Python List index()
Python int()
Python Program to Create Pyramid Patterns
Python repr()
Python Program to Check if a Number is Positive, Negative or 0
Python Inheritance
Python frozenset()
Python getattr()
Python Program to Count the Number of Occurrence of a Character in String
Python List extend()
Python Set union()
Python hex()
Python Program to Catch Multiple Exceptions in One Line
Python bytes()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python property()
Python String isprintable()
Python Program to Compute all the Permutation of the String
Python Namespace and Scope
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Differentiate Between type() and isinstance()
Python Program to Illustrate Different Set Operations
Python Program to Remove Punctuations From a String
Python pow()
Python Numbers, Type Conversion and Mathematics
Python Deep Learning Cookbook - Indra den Bakker
Python Program to Get the Full Path of the Current Working Directory