You can download this code by clicking the button below.
This code is now available for download.
The function generates a random path starting from a specified root path, containing a random number of directories and files. The names of directories and files are randomly generated, and the file extensions come from an optional list of extensions.
Technology Stack : Pathlib
Code Type : Function
Code Difficulty : Intermediate
import random
from pathlib import Path
def random_path_length(root_path, extensions=None):
"""
Generate a random path with a random length, starting from the given root_path.
The path will contain a random number of directories and files with random extensions.
Args:
root_path (Path): The root path from which to generate the random path.
extensions (list of str, optional): List of file extensions to be used for files. Defaults to None.
Returns:
Path: A randomly generated path.
"""
if extensions is None:
extensions = ['.txt', '.py', '.json', '.jpg', '.pdf']
num_dirs = random.randint(2, 5)
num_files = random.randint(1, 3)
current_path = root_path
for _ in range(num_dirs):
new_dir = Path(f"dir_{random.randint(1, 100)}")
current_path = current_path / new_dir
for _ in range(num_files):
ext = random.choice(extensions)
new_file = Path(f"file_{random.randint(1, 100)}{ext}")
current_path = current_path / new_file
return current_path
# Code Information