grep value files - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: grep value files (/thread-24788.html) |
grep value files - enigma619 - Mar-04-2020 Hi Quick question: for you what is the best way in a python script to grep a word / value in all directory files (reccursively)? I have seen many means to do but not sure what is the best proper mean to do iti. Thanks import os keyword = "name" root_dir = "/bla" for root, dirs, files in os.walk(root_dir, onerror=None): for filename in files: file_path = os.path.join(root, filename) try: with open(file_path, "rb") as f: # read the file line by line for line in f: try: line = line.decode("utf-8") except ValueError: continue if keyword in line: print (keyword) print(file_path) break except (IOError, OSError): pass |