Reading folders recursively in Python

85 views Asked by At

The purpose of this program is to recursively look through all the files and directories in a root directory to find any matches of a key phrase (named file in main method). My main issue is that I cannot figure out how to get into the subdirectories and make sure I loop through all of the files and directories in it, and then continue doing so until I've went through all directories in the tree that started from the root directory.

Here is my current code.

import os
import sys

def search_dir(path):
    for root, dirs, files in os.walk(os.path.abspath(path)):
        for f in files:
            if file in f:
                print("File : {}".format(os.path.join(root, f)))
        for d in dirs:
            if file in d:
                print("Dir  : {}".format(os.path.join(root, d)))

def main(file, path):
    print("Starting search for '{}'\n".format(file))
    search_dir(path)
    print("\nDone Searching")


if __name__ == "__main__":
    if len(sys.argv)!=3:
        print("Usage: python find_file.py [path] [file]")
    else:
        path, file = sys.argv[1], sys.argv[2]
        main(file, path)

I've tried changing directories using os.chdir(new_path) but I end up running into problems as I get lost on when to change directories back etc. I feel as though there is a way to recursively use the search_dir function, but after much thought I cannot execute it correctly.

1

There are 1 answers

1
inspectorG4dget On BEST ANSWER

This should do it:

import os

def search_dir(root, search):
    for root, _dirnames, fnames in os.walk(root):
        for fname in fnames:
            fpath = os.path.join(root, fname)
            with open(fpath) as infile:
                if any(search in line for line in infile):
                    print("Search term found in", fpath)


if _name__ == "__main__":
    if len(sys.argv)!=3:
        print("Usage: python find_file.py [path] [searchTerm]")
    else:
        path, search = sys.argv[1], sys.argv[2]
        main(file, search)