Python Utility Functions: Random String, Directory Management, and Time

  • Share this:

Code introduction


This code block contains four functions: generating a random string, creating a directory, copying a file, deleting a directory, and getting the current time. These functions are all implemented using Python's built-in libraries.


Technology Stack : os, string, shutil, datetime

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import os
import shutil
import datetime

def random_string(length=10):
    return ''.join(random.choice(string.ascii_lowercase) for i in range(length))

def create_directory(path):
    if not os.path.exists(path):
        os.makedirs(path)
    return path

def copy_file(src, dest):
    shutil.copy2(src, dest)

def delete_directory(path):
    if os.path.exists(path):
        shutil.rmtree(path)

def current_time():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")