You can download this code by clicking the button below.
This code is now available for download.
This code combination demonstrates how to use Python's built-in libraries to perform a series of different tasks, including generating a random string, listing files in a directory, getting the current time, validating an email address, counting the occurrences of a substring in text, and converting data to JSON format.
Technology Stack : os, sys, time, datetime, json, re, random, string
Code Type : Code combination
Code Difficulty : Intermediate
import os
import sys
import time
import datetime
import json
import re
import random
import string
def generate_random_string(length=10):
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def list_files(directory):
return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
def get_current_time():
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def validate_email(email):
regex = r'^\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
return re.match(regex, email) is not None
def count_occurrences(text, substring):
return text.count(substring)
def json_dumps(data, indent=4):
return json.dumps(data, indent=indent)