Python: List Subdirectories in Directory

To access subdirectories in a directory, you can use Python’s os module. Use the os.listdir() function to retrieve all files and folders in the directory, and then use the os.path.isdir() function to check if it is a folder.

Here is an example code:

import os

def get_subdirectories(directory):
    subdirectories = []
    for item in os.listdir(directory):
        if os.path.isdir(os.path.join(directory, item)):
            subdirectories.append(item)
    return subdirectories

directory = "/path/to/directory"
subdirectories = get_subdirectories(directory)
print(subdirectories)

To access all files and folders in a directory in the code, use the os.listdir() function. Then, use the os.path.isdir() function to determine if it’s a folder. If it’s a folder, add it to the subdirectories list. Finally, print out the list of subdirectories.

Simply replace “/path/to/directory” with the actual directory path.

bannerAds