Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open all .txt and .log files in the current directory, search, and print the file the search was found

I'm trying to search for a string in all text and log files in the current directory. And if it finds a match, print the text or log file where the match was found. Is this possible, and how can I manipulate the code below to accomplish this task?

  fiLe = open(logfile, "r")
  userString = raw_input("Enter a string name to search: ")
  for line in fiLe.readlines():
      if userString in line:
         print line
like image 917
suffa Avatar asked Apr 26 '11 14:04

suffa


3 Answers

Something like this:

import os
directory = os.path.join("c:\\","path")
for root,dirs,files in os.walk(directory):
    for file in files:
       if file.endswith(".log") or file.endswith(".txt"):
           f=open(file, 'r')
           for line in f:
              if userstring in line:
                 print "file: " + os.path.join(root,file)             
                 break
           f.close()
like image 187
ghostdog74 Avatar answered Sep 21 '22 12:09

ghostdog74


He asked for a flat readdir, not for a recursive file tree walk. os.listdir() does the job.

like image 34
Jürgen Weigert Avatar answered Sep 22 '22 12:09

Jürgen Weigert


Do you have to do it in Python? Otherwise, simply grep -l "string" *.txt *.log would work.

like image 38
Noufal Ibrahim Avatar answered Sep 24 '22 12:09

Noufal Ibrahim