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 *args and **kwargs
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Randomly Select an Element From the List
Python frozenset()
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Print Output Without a Newline
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python String isdecimal()
Python tuple()
Python List index()
Python Program to Find the Factors of a Number
Python Program to Solve Quadratic Equation
Python Program to Check If a String Is a Number (Float)
Python Program Read a File Line by Line Into a List
Python Closures
Python Operators
Python Program to Get the Class Name of an Instance
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python if...else Statement
Python Set remove()
Python Program to Get a Substring of a String
Python Function Arguments
Python print()
Python callable()
Python divmod()
Python String islower()
Python Program to Sort Words in Alphabetic Order
Python Namespace and Scope
Python ord()
Python Keywords and Identifiers
Introduction to Scientific Programming with Python - Joakim Sundnes
Python complex()