suffa
suffa

Reputation: 3806

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

Upvotes: 7

Views: 21854

Answers (3)

Jürgen Weigert
Jürgen Weigert

Reputation: 2728

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

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 342869

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()

Upvotes: 18

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72815

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

Upvotes: 2

Related Questions