Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
grep value files
#1
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  use subprocess on linux\pi wwith a "grep " command korenron 2 7,901 Oct-19-2021, 10:52 AM
Last Post: DeaD_EyE
  How to grep corresponding value in another df Mekala 2 1,827 Oct-13-2020, 02:52 PM
Last Post: Mekala
  2 forms of this tool grep command Lylyhannah 0 1,948 Jan-21-2019, 08:21 AM
Last Post: Lylyhannah
  grep command based on lines in a pattern file Skaperen 1 2,159 Jan-07-2019, 10:23 AM
Last Post: Gribouillis
  windows grep messed up Larz60+ 4 4,450 Mar-27-2017, 01:58 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020