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 Illustrate Different Set Operations
Python Program to Check If a String Is a Number (Float)
Python iter()
Python Operators
Python Program to Create Pyramid Patterns
Python isinstance()
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Convert Two Lists Into a Dictionary
Python Program to Get File Creation and Modification Date
Python @property decorator
Python String istitle()
Python Data Types
Python Set intersection()
Python List copy()
Python delattr()
Python Global Keyword
Python String translate()
Python Dictionary fromkeys()
Python getattr()
Python Program to Transpose a Matrix
Python Program to Check the File Size
Python Set union()
Python Program to Shuffle Deck of Cards
Node.js vs Python for Backend Development
Python Program to Make a Flattened List from Nested List
Python Anonymous / Lambda Function
Python Dictionary setdefault()
Python Multiple Inheritance
Python Program to Check If a List is Empty
Python divmod()
Python locals()
Python Program to Check Whether a String is Palindrome or Not