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:
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Merge Two Dictionaries
Python Type Conversion and Type Casting
Python Errors and Built-in Exceptions
Python Program to Append to a File
Python Program to Remove Punctuations From a String
Python filter()
Deep Learning with Python - Francois Cholletf
How to Get Started With Python?
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python locals()
Python Set pop()
Python slice()
Python Program to Find Hash of File
Python String isalpha()
Python Program to Get the File Name From the File Path
Python Program to Safely Create a Nested Directory
Python String rstrip()
Python Program to Delete an Element From a Dictionary
Python String lower()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python String count()
Python Iterators
Python Program to Remove Duplicate Element From a List
Python Program to Concatenate Two Lists
Python globals()
Python sum()
Python Program to Find the Factorial of a Number
Python Program to Differentiate Between del, remove, and pop on a List
Python Set symmetric_difference_update()
Python Set isdisjoint()
Python RegEx