Iterating directories in python with os.walk

os.walk takes care of the details, and on every pass of the loop, it gives us three things:

dirName: The next directory it found.
subdirList: A list of sub-directories in the current directory.
fileList: A list of files in the current directory.

The directory structure is as below, obtained from command tree in windows :

C:\>tree /F MainDirectory
Folder PATH listing
Volume serial number is 00000079 F859:0937
C:\MAINDIRECTORY
├───subDirectory1
│   │   file11.txt
│   │   file12.txt
│   │
│   └───subToSubDirectory1
│           file1.txt
│           file2.txt
│           file3.txt
│           file4.txt
│           file5.txt
│           file6.txt
│
└───subDirectory2
        file22.txt
        file23.txt
        file24.txt

Example :

# Import the os module, os.walk function is in this module
import os
 
# Set the directory you want to start from
rootDir = 'C:\\MainDirectory'

for dirName, subdirList, fileList in os.walk(rootDir):
    print('Found directory: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)

Output :

pydev debugger: starting
Found directory: C:\MainDirectory
Found directory: C:\MainDirectory\subDirectory1
	file11.txt
	file12.txt
Found directory: C:\MainDirectory\subDirectory1\subToSubDirectory1
	file1.txt
	file2.txt
	file3.txt
	file4.txt
	file5.txt
	file6.txt
Found directory: C:\MainDirectory\subDirectory2
	file22.txt
	file23.txt
	file24.txt