Random String Generator with Time and File Save

  • Share this:

Code introduction


This function generates a random string, records the current time, saves the data to a file, and finally returns the content read from the file.


Technology Stack : Built-in libraries: math, random, string, datetime, os, sys, json

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import math
import random
import string
import datetime
import os
import sys
import json

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

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

def save_to_file(data, filename):
    with open(filename, 'w') as f:
        json.dump(data, f)

def read_from_file(filename):
    with open(filename, 'r') as f:
        return json.load(f)

def system_info():
    info = {
        'platform': sys.platform,
        'version': sys.version,
        'executable': sys.executable,
        'path': os.environ['PATH']
    }
    return info

def xxx(arg1, arg2):
    # Example function that takes two arguments and returns a random string of a specified length
    random_str = random_string(arg1)
    current_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S')
    data_to_save = {
        "time": current_time,
        "random_string": random_str
    }
    save_to_file(data_to_save, 'output.json')
    return read_from_file('output.json')