Python Utility Functions Overview

  • Share this:

Code introduction


This code block contains five different functions: generate_random_string, get_file_size, find_all_emails, load_json_file, and get_current_time.


Technology Stack : random, string, os, re, json, datetime

Code Type : Code combination

Code Difficulty : Intermediate


                
                    
import random
import string
import os
import re
import json
import datetime

def generate_random_string(length):
    if not isinstance(length, int) or length < 1:
        raise ValueError("Length must be a positive integer")
    
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(length))

def get_file_size(file_path):
    if not os.path.exists(file_path):
        raise FileNotFoundError("The file does not exist")
    
    return os.path.getsize(file_path)

def find_all_emails(text):
    email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    return re.findall(email_pattern, text)

def load_json_file(file_path):
    if not os.path.exists(file_path):
        raise FileNotFoundError("The file does not exist")
    
    with open(file_path, 'r') as file:
        return json.load(file)

def get_current_time():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")