Python Utility Functions Overview

  • Share this:

Code introduction


This code snippet includes multiple functions using built-in Python libraries, such as SHA256 hash calculation, timestamp generation, filtering non-ASCII characters, reading file content, pausing program execution, and writing JSON data to a file.


Technology Stack : hashlib, datetime, re, os, sys, time, json

Code Type : Code function

Code Difficulty : Intermediate


                
                    
import random
import os
import sys
import time
import datetime
import json
import hashlib
import re

def sha256_hash(input_string):
    """Calculate SHA256 hash of a string."""
    hash_object = hashlib.sha256(input_string.encode())
    return hash_object.hexdigest()

def generate_timestamp():
    """Generate a timestamp in ISO format."""
    return datetime.datetime.now().isoformat()

def filter_non_ascii(text):
    """Filter out non-ASCII characters from a string."""
    return re.sub(r'[^\x00-\x7F]+', '', text)

def read_file_content(file_path):
    """Read the content of a file and return it as a string."""
    with open(file_path, 'r') as file:
        return file.read()

def sleep_seconds(seconds):
    """Pause the execution of the program for the specified number of seconds."""
    time.sleep(seconds)

def write_json(data, file_path):
    """Write JSON data to a file."""
    with open(file_path, 'w') as file:
        json.dump(data, file)

def sha256_hash(input_string):
    """Calculate SHA256 hash of a string."""
    hash_object = hashlib.sha256(input_string.encode())
    return hash_object.hexdigest()

def generate_timestamp():
    """Generate a timestamp in ISO format."""
    return datetime.datetime.now().isoformat()

def filter_non_ascii(text):
    """Filter out non-ASCII characters from a string."""
    return re.sub(r'[^\x00-\x7F]+', '', text)

def read_file_content(file_path):
    """Read the content of a file and return it as a string."""
    with open(file_path, 'r') as file:
        return file.read()

def sleep_seconds(seconds):
    """Pause the execution of the program for the specified number of seconds."""
    time.sleep(seconds)

def write_json(data, file_path):
    """Write JSON data to a file."""
    with open(file_path, 'w') as file:
        json.dump(data, file)