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 String join()
Python Program to Print all Prime Numbers in an Interval
Python Program to Check Armstrong Number
Python Exception Handling Using try, except and finally statement
Python Program to Split a List Into Evenly Sized Chunks
Python Operators
Python max()
Python String isalpha()
Python String islower()
Python Program to Find Factorial of Number Using Recursion
Python List index()
Python Program to Transpose a Matrix
Introduction to Scientific Programming with Python - Joakim Sundnes
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Set issubset()
Python Recursion
Python Program to Check if a Number is Odd or Even
Python String count()
Python open()
How to get current date and time in Python?
Python Set union()
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Print the Fibonacci sequence
Python iter()
Python String isalnum()
Python String isdigit()
Python hex()
Python Program to Calculate the Area of a Triangle
Python list()
Python Decorators
Python slice()