Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir="C:/Users/sid/Desktop/test"

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir="C:/Users/sid/Desktop/test"

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

Leave a Comment