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 Directory and Files Management
How to get current date and time in Python?
Python memoryview()
Python Type Conversion and Type Casting
Python divmod()
Python Tuple
Python List remove()
Python List extend()
Python Matrices and NumPy Arrays
Python Set issuperset()
Python bytes()
Python Program Read a File Line by Line Into a List
Python time Module
Python Program to Merge Mails
Python Program to Add Two Numbers
Python String rstrip()
Python Program to Get Line Count of a File
Python String lower()
Python Global Keyword
Python Anonymous / Lambda Function
Python Exception Handling Using try, except and finally statement
Python repr()
Python help()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python frozenset()
Python String zfill()
Python Program to Illustrate Different Set Operations
Python hash()
Python exec()
Python String isprintable()
Python pow()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth