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 Program to Randomly Select an Element From the List
Python Set issuperset()
Python open()
Python String title()
Deep Learning with Python - Francois Cholletf
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python while Loop
Python print()
Python next()
Python ascii()
Python Tuple index()
Python String isalpha()
Python dict()
Python Keywords and Identifiers
Python Program to Print Hello world!
Python any()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python property()
Python Global Keyword
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python String center()
Python Set difference()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Convert Two Lists Into a Dictionary
Python Namespace and Scope
Python Program to Find Factorial of Number Using Recursion
Python Program to Convert Kilometers to Miles
Python Set discard()
Python Multiple Inheritance
Python String swapcase()
Machine Learning with Python for everyone - Mark E.Fenner
Python format()