7

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
tshepang
  • 12,111
  • 21
  • 91
  • 136
suffa
  • 3,606
  • 8
  • 46
  • 66

3 Answers3

18

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()
jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • In windows would the walk method be like os.walk('c:/Python27') or something along those lines? Thanks! – suffa Apr 26 '11 at 14:50
  • Note that `str.endswith(suffix[, start[, end]])` can take a tuple for suffix. Could get cumbersome with too many "or" comparisons. – two7s_clash Oct 18 '16 at 19:29
3

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

Jürgen Weigert
  • 2,618
  • 1
  • 16
  • 13
2

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

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
  • lbrahim yeah, I need to to do this in Python. Thanks for the info! – suffa Apr 26 '11 at 14:52
  • 2
    @Andre Caron It looks like a legitimate question ... you must be bright when you can hear text! ... and who are you to determine what it sounds like? Lad, I finished school long ago ... this is a self-interest hobby. Nothing better to do with your time then to bring negativity. People like you .... – suffa Apr 26 '11 at 15:23