Skip to content

Instantly share code, notes, and snippets.

@jcarlosroldan
Last active February 13, 2018 12:21
Show Gist options
  • Save jcarlosroldan/e5dc2d9c646a9d1c3a0fb1c175a6e1be to your computer and use it in GitHub Desktop.
Save jcarlosroldan/e5dc2d9c646a9d1c3a0fb1c175a6e1be to your computer and use it in GitHub Desktop.
Recursive search by content
"""
Recursive search by file content.
By Juan C. Roldán (https://juancroldan.com/)
Just change WORDS to whichever strings you are looking for.
"""
from os import listdir
from os.path import isdir
WORDS = ["this is a test", "localhost"]
def search(words, path = "."):
res = []
for f in listdir(path):
child_path = path + "/" + f
if isdir(child_path):
res.extend(search(words, child_path))
else:
with open(child_path, "r", encoding = "utf-8", errors = "ignore") as fp:
data = fp.read()
if any(word in data for word in words):
res.append(child_path)
return res
print("\n".join(search(WORDS)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment