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 locals()
Python Program to Find the Largest Among Three Numbers
Python reversed()
Python Shallow Copy and Deep Copy
Python Program to Print Hello world!
Python issubclass()
Python Program to Get the Class Name of an Instance
Python Program to Get a Substring of a String
Python Program to Check if a Number is Odd or Even
Python Program to Measure the Elapsed Time in Python
Python Program to Display Powers of 2 Using Anonymous Function
Python zip()
Python Matrices and NumPy Arrays
Python list()
Python Program to Add Two Matrices
Python bool()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Print Colored Text to the Terminal
Python Program to Multiply Two Matrices
Python String rfind()
Python next()
Python Program to Append to a File
Python frozenset()
Python Program to Count the Number of Occurrence of a Character in String
Python dict()
Python File I/O Operation
Deep Learning in Python - LazyProgrammer
Python Program to Get File Creation and Modification Date
Python Program to Convert Bytes to a String
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Find HCF or GCD
Python Set remove()