How do I extract the names of several folders within a directory?

2

I need to enter into a folder called / users , where inside it to several folder and copy the name of all folders, follow the example.

I wanted to be able to get the name of these folders and save them to a list in python.

    
asked by anonymous 17.05.2018 / 19:49

1 answer

2

You can use the listdir . This function will return all files and all directories within the specified directory.

To check if the item is a directory, you can use the < strong> isdir . Note that this function needs to be given the complete path of the item to be checked and that the return of listdir are relative paths , so use the join to concatenate the base directory name with the name of the item to check.

from os import listdir
from os.path import isdir, join

base_dir = '/users'

diretorios = [a for a in listdir(base_dir) if isdir(join(base_dir, a))]
    
17.05.2018 / 20:03