List Subdirectories in a Given Path

  • Share this:

Code introduction


This function accepts a path argument and returns a list of all subdirectories within the given directory path. It uses the Pathlib library to traverse directories.


Technology Stack : Pathlib

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from pathlib import Path, PurePosixPath

def list_subdirectories(path):
    """
    List all subdirectories within a given directory path.

    Args:
        path (Path or str): The directory path to list subdirectories from.

    Returns:
        list: A list of pathlib.PurePosixPath objects representing the subdirectories.
    """
    try:
        path = Path(path)
        subdirectories = [subdir for subdir in path.iterdir() if subdir.is_dir()]
        return list(subdirectories)
    except Exception as e:
        print(f"An error occurred: {e}")
        return []

# JSON Explanation                
              
Tags: