user18726875
user18726875

Reputation:

How to append subdirectories to a list in python

I would like to know how I can only append sub-directories of a given directory to a list in Python.

Something like this is not what I'm searching for as it outputs the files:

filelist = []
for root, dirs, files in os.walk(job['config']['output_dir']):
    for file in files:
        # append the file name to the list
        filelist.append(os.path.join(root, file))
# print all the file names
for name in filelist:
    print(name)

Upvotes: 0

Views: 957

Answers (1)

Rodrigo Llanes
Rodrigo Llanes

Reputation: 640

Just use the dirs variable instead the files variable, like this:

dirs_list = []
for root, dirs, files in os.walk('test'):
    for dir in dirs:
        dirs_list.append(os.path.join(root, dir))

print(dirs_list)

Upvotes: 1

Related Questions