Code introduction
This collection of functions demonstrates how to use Python's built-in libraries to perform various common programming tasks, including generating random strings, listing files in a directory, replacing file extensions, calculating age, removing duplicates from a list, counting vowels in a string, unzipping multiple lists, sorting words by length, checking if a string is a palindrome, and reading/writing JSON files.
Technology Stack : os, re, json, sys, time, shutil, random, string, math, datetime
Code Type : Function set
Code Difficulty : Intermediate
import os
import re
import json
import sys
import time
import shutil
import random
import string
import math
import datetime
def generate_random_string(length):
return ''.join(random.choice(string.ascii_lowercase) for i in range(length))
def list_files_in_directory(directory):
return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
def replace_extension(file_path, new_extension):
return os.path.splitext(file_path)[0] + new_extension
def calculate_age(birthdate):
today = datetime.date.today()
return today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
def remove_duplicates_from_list(lst):
return list(dict.fromkeys(lst))
def count_vowels_in_string(s):
return sum(1 for c in s if c in 'aeiouAEIOU')
def zip_multiple_lists(lists):
return zip(*lists)
def sort_words_by_length(words):
return sorted(words, key=len)
def is_palindrome(s):
return s == s[::-1]
def read_json_file(file_path):
with open(file_path, 'r') as f:
return json.load(f)
def write_json_file(data, file_path):
with open(file_path, 'w') as f:
json.dump(data, f, indent=4)