×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Extracting extension from filename in Python

By Sapna Deraje Radhakrishna Last updated : December 21, 2024

Python provides built in module to extract the file extension from the file name.

Before Python 3

The os.path module provides a function called splitext method, which splits the pathname path into file name and file extension.

Example

>>> import os
>>> file_name = 'includehelp.txt'
>>> print(os.path.splitext(file_name))
('includehelp', '.txt')
>>> 

After Python 3

In the path from pathlib, using the suffix method.

Example

from pathlib import Path

# Define the file name
file_name = "example.txt"

# Get the file extension
file_extension = Path(file_name).suffix

# Print the file extension
print(file_extension)

Output

.txt

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.