Python Functions for Common Tasks

  • Share this:

Code introduction


This collection of functions demonstrates how to use Python's built-in libraries to complete common tasks, including generating random strings, calculating time, creating directories, calculating the circumference of a circle, reading and writing files, and handling JSON data.


Technology Stack : random, string, time, os, math, open, json

Code Type : Function set

Code Difficulty : Intermediate


                
                    
import random
import string
import time
import os
import math

def generate_random_string(length=10):
    """
    Generate a random string of specified length.
    """
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(length))

def count_seconds_since_epoch():
    """
    Return the number of seconds since the epoch.
    """
    return int(time.time())

def create_directory(path):
    """
    Create a directory at the specified path.
    """
    os.makedirs(path, exist_ok=True)

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

def read_file(file_path):
    """
    Read the contents of a file.
    """
    with open(file_path, 'r') as file:
        return file.read()

def write_file(file_path, content):
    """
    Write content to a file.
    """
    with open(file_path, 'w') as file:
        file.write(content)

def json_dumps(data):
    """
    Convert a Python object into a JSON string.
    """
    import json
    return json.dumps(data)

def json_loads(json_str):
    """
    Convert a JSON string into a Python object.
    """
    import json
    return json.loads(json_str)