How to scan through a directory recursively in Python?

PythonServer Side ProgrammingProgramming

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.

raja
Published on 27-Dec-2017 06:59:18
Advertisements