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 bin()
Python Global Keyword
Python Program to Display Fibonacci Sequence Using Recursion
Python id()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Check Armstrong Number
Python Closures
Python List reverse()
Python String title()
Python Program to Return Multiple Values From a Function
Python String startswith()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python set()
Python Dictionary clear()
Python Program to Differentiate Between del, remove, and pop on a List
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Program to Convert Decimal to Binary Using Recursion
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Directory and Files Management
Node.js vs Python for Backend Development
Python Multiple Inheritance
Python Program to Make a Simple Calculator
Python Program to Find Numbers Divisible by Another Number
Python staticmethod()
Python sorted()
Python String zfill()
Python bytes()
Python repr()
Python strftime()
Python Namespace and Scope
Python String ljust()
Python List count()