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 Find the Factors of a Number
Python Program to Display Calendar
Python Program to Count the Occurrence of an Item in a List
Python classmethod()
Python Dictionary fromkeys()
Python Package
Python Program to Count the Number of Occurrence of a Character in String
Python format()
Python print()
Python Program to Print the Fibonacci sequence
Python Program to Capitalize the First Character of a String
Python Program to Display Fibonacci Sequence Using Recursion
Python String maketrans()
Python Tuple
Python Program to Get the File Name From the File Path
Python issubclass()
Python Program to Find the Largest Among Three Numbers
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python tuple()
Python Program to Convert String to Datetime
Python memoryview()
Python next()
Python isinstance()
Python Set pop()
Python Namespace and Scope
Python Program to Convert Celsius To Fahrenheit
Python Directory and Files Management
Python Set isdisjoint()
Python List copy()
Python Set update()
Python complex()