Python Utility Functions Overview

  • Share this:

Code introduction


This code block contains a series of functions implemented using Python's built-in libraries, covering various aspects such as string processing, file operations, network operations, encryption encoding, date and time operations, regular expressions, email processing, and locale settings.


Technology Stack : random, string, os, sys, time, datetime, json, hashlib, html, re, io, socket, urllib, mimetypes, email, base64, binascii, locale

Code Type : String generation, time formatting, string hashing, HTML escape, regular expression matching, file manipulation, MIME type detection, email parsing, Base 64 encoding, hexadecimal conversion, locale detection

Code Difficulty : Intermediate


                
                    
import random
import string
import os
import sys
import time
import datetime
import json
import hashlib
import html
import re
import io
import socket
import urllib.request
import urllib.parse
import urllib.error
import mimetypes
import email
import base64
import binascii
import locale

def generate_random_string(length=10):
    """
    Generate a random string of a given length.
    """
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

def get_current_time_formatted():
    """
    Get the current time in a formatted string.
    """
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def hash_string(input_string, hash_type='sha256'):
    """
    Hash a string using a specified hash type.
    """
    if hash_type == 'sha256':
        return hashlib.sha256(input_string.encode()).hexdigest()
    elif hash_type == 'md5':
        return hashlib.md5(input_string.encode()).hexdigest()
    else:
        raise ValueError("Unsupported hash type. Please use 'sha256' or 'md5'.")

def escape_html(input_string):
    """
    Escape HTML entities in a string.
    """
    return html.escape(input_string)

def find_all_matches(input_string, pattern):
    """
    Find all matches of a pattern in a string.
    """
    return re.findall(pattern, input_string)

def save_to_file(file_path, data):
    """
    Save data to a file.
    """
    with open(file_path, 'w') as file:
        file.write(data)

def get_file_mime_type(file_path):
    """
    Get the MIME type of a file.
    """
    return mimetypes.guess_type(file_path)[0]

def parse_email(email_string):
    """
    Parse an email string into a dictionary.
    """
    return email.parser.Parser().parsestr(email_string)

def base64_encode(data):
    """
    Encode data in base64.
    """
    return base64.b64encode(data).decode()

def hexlify(data):
    """
    Convert data to hexadecimal representation.
    """
    return binascii.hexlify(data).decode()

def get_locale():
    """
    Get the current locale.
    """
    return locale.getlocale()