How do I extract the name of multiple folders within a directory?

Asked

Viewed 278 times

2

I need to get inside a folder called /users, where inside it the various folder and copy the name of all folders, follows the example.

Este é o caminho que até as pastas

I wish I could take the name of these folders and save to a list in python.

1 answer

2


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

To check if the item is a directory, you can use the function isdir. Note that this function needs to receive the path as a parameter complete of the item to be checked and that the return of listdir are paths relative, then one should use the function join to concatenate the name of the base directory with the name of the item to be checked.

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))]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.