Advertisement
Guest User

Untitled

a guest
Jul 31st, 2015
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. """
  2. " Created by Daniele Costarella <daniele.costarella@gmail.com>
  3. " Search file contents in multiple subdirectories
  4. """
  5.  
  6. import os
  7.  
  8. def find(word):
  9. def _find(path):
  10. with open(path, "rb") as fp:
  11. for n, line in enumerate(fp):
  12. if word in line:
  13. yield n+1, line
  14. return _find
  15.  
  16. def search(word, start):
  17. finder = find(word)
  18. for root, dirs, files in os.walk(start):
  19. for f in files:
  20. path = os.path.join(root, f)
  21. for line_number, line in finder(path):
  22. yield path, line_number, line.strip()
  23.  
  24. if __name__ == "__main__":
  25. import sys
  26. if not len(sys.argv) == 3:
  27. print("USAGE: python find.py word directory")
  28. sys.exit(1)
  29. word = sys.argv[1]
  30. start = sys.argv[2]
  31. for path, line_number, line in search(word, start):
  32. print ("{0} matches in line {1}: '{2}'".format(path, line_number, line))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement