Python Utility Functions Collection

  • Share this:

Code introduction


A collection of custom functions using Python's built-in libraries, including generating random strings, finding files with a specific extension, extracting email addresses from text, measuring function execution time, sorting numbers, generating unique identifiers, reading file content, and getting system information.


Technology Stack : math, os, re, sys, time, random, sorted, open, os.path, time.time, random.choices

Code Type : Code collection

Code Difficulty : Intermediate


                
                    
import math
import os
import re
import sys
import time
import random

def generate_random_string(length):
    letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    return ''.join(random.choice(letters) for i in range(length))

def find_files_with_extension(directory, extension):
    matches = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(extension):
                matches.append(os.path.join(root, file))
    return matches

def extract_emails(text):
    email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
    return re.findall(email_pattern, text)

def measure_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time} seconds to execute.")
        return result
    return wrapper

def sort_numbers(numbers):
    return sorted(numbers)

def generate_unique_id(length=8):
    return ''.join(random.choices('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', k=length))

def read_file_content(file_path):
    with open(file_path, 'r') as file:
        return file.read()

def get_system_info():
    return {
        'platform': sys.platform,
        'version': sys.version,
        'path': os.path,
        'time': time.time()
    }