Explain Codes LogoExplain Codes Logo

How can I check the extension of a file?

python
file-handling
pathlib
file-extension
Alex KataevbyAlex Kataev·Feb 9, 2025
TLDR

The os.path.splitext() function in Python splits the filename into its name and extension:

import os # Get extension of 'example.txt' or 'final_draft_v2_FINAL.txt' print(os.path.splitext('example.txt')[1]) # Output: .txt

This snippet is a direct and efficient way to extract just the extension.

We can add case-insensitivity and multi-extension handling for an enhanced file extension check:

filename = 'example.TXT' extension = os.path.splitext(filename)[1].lower() # Normalize to lowercase if extension == '.txt': print("Found a TXT. The Treasure-X-Trove.") elif extension in ('.jpg', '.jpeg', '.png'): print("Look, a wild Image file appears!")

Extracting an extension with pathlib

Use pathlib for a modern and cleaner approach to file handling in Python:

from pathlib import Path # Using pathlib to get the file extension file_path = Path('example.txt') if file_path.suffix.lower() == '.txt': print(f"The file {file_path.name} may contain secrets.")

Pathlib can also differentiate files from directories, ensuring you aren't trying to read a folder as if it were a user manual.

Finding a pattern with fnmatch

To check multiple similar extensions, use the fnmatch module for its pattern matching capabilities:

import fnmatch import os for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print(f"{file} - Doctor, we've got a txt!")

Pattern recognition with glob

The glob module simplifies fetching files by their extensions, even from nested directories:

import glob # Retrieve all .txt files in the current directory text_files = glob.glob('*.txt') for file in text_files: print(f"{file}: Why can't a bicycle stand up by itself? Because it's two-tired.")

Because, why not throw in a bicycle pun while traversing a directory?

A smarter way to handle file types

To streamline code logic and avoid an ugly if-elif chain when dealing with various types of files, use this clever trick:

file_ext_actions = { '.txt': process_text_file, # Whisperer of Text Files '.jpg': process_image_file, # JPEG Janitor '.png': process_image_file, # PNG Paramedic '.pdf': process_pdf_file, # PDF Pirate } file_ext = os.path.splitext('example.txt')[1] # Extracting the life purpose of a file action = file_ext_actions.get(file_ext.lower()) # Deciding its fate... if action: action() # Unleashing the file to its destined path else: print("Unsupported file type. Maybe we're just too advanced?")

These extension-specific functions now define the destiny of each type of file in the universe of programming.