Recursively Get Files and Directories in a Directory in Python 3

The os.walk function helps to recursively list files and directories.

The following code:

import os

for dirpath, dirs, files in os.walk('c:/walk'):
    print("{0}   [{1}]   [{2}]".format(dirpath, ','.join(dirs), ','.join(files)))

yields:

c:/walk   [1,3]   [a.txt]
c:/walk\1   [2]   [b.txt,c.txt]
c:/walk\1\2   []   [d.txt]
c:/walk\3   []   [e.txt]

where c:/walk is:

a windows explorer dialog with two directories and a file in it

and c:/walk/1 is:

a windows explorer dialog with a directory and two files

To walk from the bottom up (subdirectories first), set the topdown parameter to False.

import os

for dirpath, dirs, files in os.walk('c:/walk', False):
    print("{0}   [{1}]   [{2}]".format(dirpath, ','.join(dirs), ','.join(files)))

The output is:

c:/walk\1\2   []   [d.txt]
c:/walk\1   [2]   [b.txt,c.txt]
c:/walk\3   []   [e.txt]
c:/walk   [1,3]   [a.txt]

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.