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 Dictionary keys()
Python String format()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Program to Measure the Elapsed Time in Python
Python __import__()
Python Set union()
Python Iterators
Python Program to Compute all the Permutation of the String
Python Dictionary setdefault()
Python String istitle()
Python String rjust()
Python String rindex()
Python Data Structures and Algorithms - Benjamin Baka
Python String replace()
Python List Comprehension
Python Tuple count()
Deep Learning with Python - Francois Cholletf
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python bytearray()
Python List pop()
Python Program to Get the Class Name of an Instance
Python Program to Count the Number of Digits Present In a Number
Python Dictionary popitem()
Python String lower()
Python Program to Print Colored Text to the Terminal
Python Program to Find HCF or GCD
Python String capitalize()
Python Set issuperset()
Python Set copy()
Python Program to Remove Punctuations From a String
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python complex()