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 property()
Python Program to Slice Lists
Python object()
Python Set issubset()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python String encode()
Python id()
Python Program to Add Two Numbers
Python Program to Differentiate Between del, remove, and pop on a List
Python Tuple index()
Python List remove()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Convert Bytes to a String
Python String split()
Python type()
Python Inheritance
Python callable()
Python String capitalize()
Python Program to Swap Two Variables
Python String center()
Python next()
Python vars()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python String strip()
Python Function Arguments
Python Set difference()
Python sorted()
Python Program to Count the Number of Digits Present In a Number
Python Iterators
Python String format_map()
Python frozenset()