开发者

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 c开发者_StackOverflowan 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


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜