Extract Directory File Extensions

  • Share this:

Code introduction


This function extracts file extensions from a directory and returns a list of them.


Technology Stack : os, re

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re

def extract_extensions_from_directory(directory_path):
    extensions = set()
    for root, dirs, files in os.walk(directory_path):
        for file in files:
            file_path = os.path.join(root, file)
            if os.path.isfile(file_path):
                match = re.search(r'\.([a-zA-Z0-9]+)$', file_path)
                if match:
                    extensions.add(match.group(1))
    return list(extensions)                
              
Tags: