Python Forum

Full Version: grep value files
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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