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:
and c:/walk/1 is:
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]
Leave a comment