我已经看到了一些如何显示行计数的示例,并尝试将这些实现到我的代码中,但没有成功我是个巨蟒新手,所以我想我还有很多东西要学有人能告诉我如何显示文件中匹配的行数吗,谢谢?

elif searchType =='3':
      print "Directory to be searched: c:\SQA_log "
      print " "
      directory = os.path.join("c:\\","SQA_log")

      regex = re.compile(r'(?:3\d){6}')
      for root,dirname, files in os.walk(directory):
         for file in files:
           if file.endswith(".log") or file.endswith(".txt"):
              f=open(os.path.join(root,file))
              for line in f.readlines():
                  searchedstr = regex.findall(line)
                  for word in searchedstr:
                     print "String found: " + word
                     print "File: " + os.path.join(root,file)
                     break
                     f.close()

最佳答案

好吧,我假设你也想输出行号为此,你应该:

  regex = re.compile(r'(?:3\d){6}')
  for root,dirname, files in os.walk(directory):
     for file in files:
       if file.endswith(".log") or file.endswith(".txt"):
          f=open(os.path.join(root,file))
          for i, line in enumerate(f.readlines()):
              searchedstr = regex.findall(line)
              for word in searchedstr:
                 print "String found: " + word
                 print "Line: "+str(i)
                 print "File: " + os.path.join(root,file)
                 break
          f.close()

09-20 05:26