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:
Java Program to Implement the Program Used in grep/egrep/fgrep
Python filter()
Python tuple()
Python Program to Convert Two Lists Into a Dictionary
Python callable()
Python Program to Differentiate Between type() and isinstance()
Python Set intersection_update()
Python Program to Merge Two Dictionaries
Python Tuple
Python Directory and Files Management
Python __import__()
Python iter()
Python Shallow Copy and Deep Copy
Python String isprintable()
Python String rsplit()
Python String expandtabs()
Python Program to Represent enum
Python frozenset()
Python Program to Find Sum of Natural Numbers Using Recursion
Python @property decorator
Python String rstrip()
Python String isdecimal()
Python Set symmetric_difference()
Python Program to Find the Factors of a Number
Python Deep Learning Cookbook - Indra den Bakker
Python slice()
Python Program to Safely Create a Nested Directory
Python Program to Add Two Matrices
Python int()
Python Program to Display the multiplication Table
Python Program to Print all Prime Numbers in an Interval
Python float()