Computer >> Computer tutorials >  >> Programming >> Python

How to scan through a directory recursively in Python?


You can use the os.walk function to walk through the directory tree in python.

example

import os
for dirpath, dirs, files in os.walk("./my_directory/"):  
            for filename in files:
                        fname = os.path.join(dirpath,filename)
                        with open(fname) as myfile:
                                    print(myfile.read())

The above program recursively moves through the my_directory tree and prints contents of each file in the tree to the console output.