Random String Generation and Directory Structure Analysis

  • Share this:

Code introduction


The function first generates a random string of specified length using the random and string modules, then analyzes the structure of the specified directory using the os module, and finally returns the directory structure in JSON format.


Technology Stack : random, string, os

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import math
import string
import json
import os
import re

def generate_random_string(length):
    if not isinstance(length, int) or length <= 0:
        raise ValueError("Length must be a positive integer")
    
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def analyze_directory_structure(path):
    if not os.path.isdir(path):
        raise ValueError("Path is not a valid directory")
    
    directory_structure = {}
    for root, dirs, files in os.walk(path):
        for name in dirs:
            directory_structure[os.path.join(root, name)] = "Directory"
        for name in files:
            directory_structure[os.path.join(root, name)] = "File"
    
    return json.dumps(directory_structure, indent=4)

def xxx(arg1, arg2):
    return generate_random_string(arg1), analyze_directory_structure(arg2)

# Example usage:
# result, structure = xxx(10, '/path/to/directory')
# print(result)
# print(structure)                
              
Tags: