You can download this code by clicking the button below.
This code is now available for download.
This code snippet demonstrates how to use Python built-in libraries to generate random strings, read files, check for prime numbers, search for patterns in text, get the current time, save data to a file, and retrieve system information.
Technology Stack : random, string, math, re, sys, time, os, json
Code Type : Function
Code Difficulty : Intermediate
import random
import string
import math
import re
import sys
import time
import os
import json
def generate_random_string(length=10):
if not isinstance(length, int) or length <= 0:
raise ValueError("Length must be a positive integer")
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
def read_file(file_path):
if not os.path.isfile(file_path):
raise FileNotFoundError("File not found")
with open(file_path, 'r') as file:
return file.read()
def is_prime(number):
if not isinstance(number, int) or number <= 1:
return False
for i in range(2, int(math.sqrt(number)) + 1):
if number % i == 0:
return False
return True
def search_pattern(text, pattern):
if not isinstance(text, str) or not isinstance(pattern, str):
raise ValueError("Text and pattern must be strings")
return re.findall(pattern, text)
def current_time():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def save_data(data, file_path):
if not isinstance(data, dict):
raise ValueError("Data must be a dictionary")
with open(file_path, 'w') as file:
json.dump(data, file)
def system_info():
info = {
'platform': sys.platform,
'version': sys.version,
'implementation': sys.implementation.name
}
return info