You can download this code by clicking the button below.
This code is now available for download.
These functions are used for generating random strings, reading file content, searching for text with regex, writing file content, calculating the circular distance between two coordinates, creating directories, loading JSON files, saving JSON data, generating timestamps, and determining if a year is a leap year.
Technology Stack : datetime, random, os, json, re, math, string
Code Type : Python custom function
Code Difficulty : Intermediate
import datetime
import random
import os
import json
import re
import math
import string
def generate_random_string(length):
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def read_file_content(file_path):
with open(file_path, 'r') as file:
return file.read()
def search_regex_in_text(pattern, text):
return re.findall(pattern, text)
def write_file_content(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
def calculate_circular_distance(coord1, coord2):
R = 6371.0 # Earth radius in kilometers
lat1, lon1 = math.radians(coord1[0]), math.radians(coord1[1])
lat2, lon2 = math.radians(coord2[0]), math.radians(coord2[1])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
def create_directory(path):
if not os.path.exists(path):
os.makedirs(path)
def load_json_file(file_path):
with open(file_path, 'r') as file:
return json.load(file)
def save_json_data(data, file_path):
with open(file_path, 'w') as file:
json.dump(data, file)
def generate_timestamp():
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)