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 Keywords and Identifiers
Python Program to Find the Square Root
Python Program to Convert Kilometers to Miles
Python Program to Find Armstrong Number in an Interval
Python complex()
Python Directory and Files Management
Python Shallow Copy and Deep Copy
Python RegEx
Python float()
Python Program to Create a Countdown Timer
Python String split()
Python Program to Make a Flattened List from Nested List
Python Set discard()
Python Program to Swap Two Variables
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Set clear()
Python Type Conversion and Type Casting
Python String encode()
Introduction to Scientific Programming with Python - Joakim Sundnes
Python while Loop
Python timestamp to datetime and vice-versa
Python next()
Python Set copy()
Python bool()
Python Iterators
Python Objects and Classes
Python Program to Trim Whitespace From a String
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Set pop()
Python Program to Find Factorial of Number Using Recursion
Python Program to Find LCM
Python id()