Python Utility Functions Collection

  • Share this:

Code introduction


The following is a collection of functions implemented using Python built-in libraries, including generating random strings, reading file content, finding all occurrences of a pattern in text, determining leap years, getting a formatted current time, writing to a file, and sorting a list by length.


Technology Stack : os, re, sys, time, datetime, random, string

Code Type : Code collection

Code Difficulty : Intermediate


                
                    
import os
import re
import sys
import time
import datetime
import random
import string

def generate_random_string(length=10):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

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

def find_all_occurrences(text, pattern):
    return [match.start() for match in re.finditer(pattern, text)]

def is_leap_year(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

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

def write_to_file(file_path, content):
    with open(file_path, 'w') as file:
        file.write(content)

def sort_list_by_length(lst):
    return sorted(lst, key=len)