Python Utility Functions for Random String, File Operations, and Time

  • Share this:

Code introduction


This code block includes a function to generate a random string, a function to read the content of a file, a function to replace special characters in text, a function to save data to a file, and a function to get the current time.


Technology Stack : os, random, string, re, json, datetime

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import random
import string
import re
import json
import datetime

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

def read_file(file_path):
    if not os.path.isfile(file_path):
        return "File does not exist."
    with open(file_path, 'r') as file:
        return file.read()

def replace_special_characters(text):
    return re.sub(r'[^a-zA-Z0-9\s]', '', text)

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

def current_time():
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')