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 String rsplit()
Python complex()
Python Program to Create a Long Multiline String
Python List append()
Python break and continue
Python Numbers, Type Conversion and Mathematics
Python vars()
Python Errors and Built-in Exceptions
Python Program to Access Index of a List Using for Loop
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python id()
Python Statement, Indentation and Comments
Python List Comprehension
Python Program to Check if a Number is Positive, Negative or 0
Python List pop()
Python Input, Output and Import
Python format()
Python ascii()
Python Program to Represent enum
Python Global, Local and Nonlocal variables
Python Program to Check if a Key is Already Present in a Dictionary
Python String rstrip()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python List count()
Python String splitlines()
Python Set intersection()
Python String rfind()
Python Custom Exceptions
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Catch Multiple Exceptions in One Line