Python Utility Functions for File, Data, and Math Operations

  • Share this:

Code introduction


This collection of functions covers file operations, data processing, string operations, date and time, random number generation, regular expressions, and mathematical calculations, suitable for developers with some Python foundation.


Technology Stack : os, re, math, random, datetime, hashlib, json, shutil

Code Type : Python function collection

Code Difficulty : Intermediate


                
                    
import os
import re
import math
import random
import datetime
import hashlib
import json
import shutil

def generate_unique_filename(base_path, extension='.txt'):
    unique_filename = hashlib.md5(str(datetime.datetime.now()).encode()).hexdigest() + extension
    unique_path = os.path.join(base_path, unique_filename)
    return unique_path

def save_data_to_file(data, file_path):
    with open(file_path, 'w') as file:
        json.dump(data, file)

def read_data_from_file(file_path):
    with open(file_path, 'r') as file:
        data = json.load(file)
    return data

def create_directory_if_not_exists(directory_path):
    if not os.path.exists(directory_path):
        os.makedirs(directory_path)

def remove_directory_if_empty(directory_path):
    if os.path.exists(directory_path):
        files = os.listdir(directory_path)
        if not files:
            shutil.rmtree(directory_path)

def list_files_in_directory(directory_path):
    return [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]

def replace_text_in_file(file_path, search_text, replacement_text):
    with open(file_path, 'r') as file:
        content = file.read()
    new_content = re.sub(search_text, replacement_text, content)
    with open(file_path, 'w') as file:
        file.write(new_content)

def calculate_distance(x1, y1, x2, y2):
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

def shuffle_list(input_list):
    random.shuffle(input_list)
    return input_list

def get_random_element_from_list(input_list):
    return random.choice(input_list)

def is_valid_email(email):
    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    return re.match(pattern, email) is not None

def get_current_time():
    return datetime.datetime.now()

def create_random_string(length, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    return ''.join(random.choice(allowed_chars) for _ in range(length))

def get_file_extension(file_path):
    return os.path.splitext(file_path)[1]

def generate_unique_filename(base_path, extension='.txt'):
    unique_filename = hashlib.md5(str(datetime.datetime.now()).encode()).hexdigest() + extension
    unique_path = os.path.join(base_path, unique_filename)
    return unique_path

def save_data_to_file(data, file_path):
    with open(file_path, 'w') as file:
        json.dump(data, file)

def read_data_from_file(file_path):
    with open(file_path, 'r') as file:
        data = json.load(file)
    return data

def create_directory_if_not_exists(directory_path):
    if not os.path.exists(directory_path):
        os.makedirs(directory_path)

def remove_directory_if_empty(directory_path):
    if os.path.exists(directory_path):
        files = os.listdir(directory_path)
        if not files:
            shutil.rmtree(directory_path)

def list_files_in_directory(directory_path):
    return [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]

def replace_text_in_file(file_path, search_text, replacement_text):
    with open(file_path, 'r') as file:
        content = file.read()
    new_content = re.sub(search_text, replacement_text, content)
    with open(file_path, 'w') as file:
        file.write(new_content)

def calculate_distance(x1, y1, x2, y2):
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

def shuffle_list(input_list):
    random.shuffle(input_list)
    return input_list

def get_random_element_from_list(input_list):
    return random.choice(input_list)

def is_valid_email(email):
    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    return re.match(pattern, email) is not None

def get_current_time():
    return datetime.datetime.now()

def create_random_string(length, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    return ''.join(random.choice(allowed_chars) for _ in range(length))

def get_file_extension(file_path):
    return os.path.splitext(file_path)[1]