I am attempting to make this function (that searches a dir for a given string) search all sub dirs as well, and do this recursively. I don’t know Python well enough to begin. Any guidance would be great.
Thanks!
def grep(regex, base_dir):
matches = list()
for filename in os.listdir(base_dir):
full_filename = os.path.join(base_dir, filename)
if not os.path.isfile(full_filename):
continue
with open(os.path.join(base_dir, filename)) as fh:
content = fh.read()
matches = matches + re.findall(regex, content)
return matches
If you’re looking to crawl an entire directory, try
os.walk(). Something like this may work (untested, but can adjust if it doesn’t work):