Random Path Generator

  • Share this:

Code introduction


This function takes a base path and one or more sub-paths, and generates a complete path by randomly combining the base path with the sub-paths.


Technology Stack : Pathlib

Code Type : File path generation

Code Difficulty : Intermediate


                
                    
import random
from pathlib import Path

def random_path_join(base_path, *paths):
    """
    Generate a random path by joining the base path with random sub-paths.
    """
    if not isinstance(base_path, Path):
        base_path = Path(base_path)
    sub_paths = [Path(str(random.choice(['folder', 'file', 'subfolder', 'document'])) + str(random.randint(1, 100))) for _ in range(random.randint(1, 5))]
    return base_path.joinpath(*sub_paths)                
              
Tags: