簡體   English   中英

如何打開當前目錄中的所有.txt和.log文件,搜索並打印找到搜索的文件

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

我正在嘗試在當前目錄中的所有文本和日志文件中搜索字符串。 如果找到匹配項,則打印找到匹配項的文本或日志文件。 這是可能的,我如何操縱下面的代碼來完成這項任務?

  fiLe = open(logfile, "r")
  userString = raw_input("Enter a string name to search: ")
  for line in fiLe.readlines():
      if userString in line:
         print line

像這樣的東西:

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

他要求一個平坦的readdir,而不是一個遞歸的文件樹步行。 os.listdir()完成這項工作。

必須用Python做嗎? 否則,只需grep -l "string" *.txt *.log就行了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM