Combining Python Libraries for Random String, PDF Search, and Age Calculation

  • Share this:

Code introduction


This function combines multiple built-in Python libraries to generate a random string, find PDF files in a specified directory, and calculate the age for a given date.


Technology Stack : os, re, random, string, datetime

Code Type : Code

Code Difficulty : Intermediate


                
                    
import os
import re
import random
import string
import datetime

def generate_random_string(length=10):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(length))

def find_files_with_extension(directory, extension):
    pattern = re.compile(f'.*{extension}$')
    return [file for file in os.listdir(directory) if pattern.match(file)]

def calculate_age(birthdate):
    today = datetime.date.today()
    return today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))

def main():
    random_str = generate_random_string(15)
    files_with_pdf = find_files_with_extension('/path/to/directory', '.pdf')
    age = calculate_age(datetime.date(1990, 1, 1))
    print(random_str)
    print(files_with_pdf)
    print(age)