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.
This should do it: