Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading