Python Utility Functions for Random String, File Search, and JSON Operations

  • Share this:

Code introduction


This function combines the functionalities of multiple Python built-in libraries to generate a random string, find files that match a given pattern, save data to a JSON file, read data from a JSON file, calculate the circumference of a circle, and generate a list of random numbers.


Technology Stack : random, string, os, re, json, math, sys

Code Type : A function that uses multiple modules

Code Difficulty : Intermediate


                
                    
import random
import string
import json
import os
import sys
import re
import math

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

def find_files(root_path, pattern):
    """Find files matching a given pattern in a directory using the os and re modules."""
    for root, dirs, files in os.walk(root_path):
        for file in files:
            if re.search(pattern, file):
                yield os.path.join(root, file)

def save_json(data, file_path):
    """Save data to a JSON file using the json module."""
    with open(file_path, 'w') as json_file:
        json.dump(data, json_file)

def read_json(file_path):
    """Read data from a JSON file using the json module."""
    with open(file_path, 'r') as json_file:
        return json.load(json_file)

def calculate_circumference(radius):
    """Calculate the circumference of a circle using the math module."""
    return 2 * math.pi * radius

def generate_random_numbers(min_value, max_value, count=1):
    """Generate a random number within a given range using the random module."""
    return [random.randint(min_value, max_value) for _ in range(count)]

def list_modules():
    """List all imported modules in the current scope using the sys module."""
    return [name for name, module in sys.modules.items() if name.startswith('random') or name.startswith('string') or name.startswith('os') or name.startswith('re') or name.startswith('json') or name.startswith('math')]

def xxx(arg1, arg2):
    """Function to demonstrate the usage of multiple modules."""
    random_string = generate_random_string(arg1)
    files = list(find_files('.', arg2))
    data = {
        "type": "random string",
        "files": files
    }
    save_json(data, 'output.json')
    loaded_data = read_json('output.json')
    circumference = calculate_circumference(arg2)
    numbers = generate_random_numbers(1, 100, arg1)
    return {
        "random_string": random_string,
        "files": files,
        "loaded_data": loaded_data,
        "circumference": circumference,
        "numbers": numbers
    }

# Example usage:
result = xxx(10, '.*\.txt$')
print(result)