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 String swapcase()
Python Program to Merge Two Dictionaries
Python list()
Python Inheritance
Python len()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Access Index of a List Using for Loop
Python Dictionary items()
Python datetime
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python round()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String rindex()
Python List reverse()
Python all()
Python List
Python String casefold()
Python String strip()
Python String isprintable()
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Sort Words in Alphabetic Order
Python Directory and Files Management
Python String join()
Python Program to Measure the Elapsed Time in Python
Python String maketrans()
Python String ljust()
Python Function Arguments
Intelligent Projects Using Python - Santanu Pattanayak
Python List copy()
Python Program to Get the Full Path of the Current Working Directory
Python Program to Print Hello world!
Python Dictionary values()