【问题标题】:How to open all .txt and .log files in the current directory, search, and print the file the search was found如何打开当前目录下所有.txt和.log文件,搜索,打印搜索到的文件
【发布时间】:2011-04-26 14:00:56
【问题描述】:

我正在尝试在当前目录中的所有文本和日志文件中搜索字符串。如果找到匹配项,则打印找到匹配项的文本或日志文件。这可能吗,我该如何操作下面的代码来完成这项任务?

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

【问题讨论】:

    标签: python search file-io


    【解决方案1】:

    类似这样的:

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

    【讨论】:

    • 在 Windows 中,walk 方法会像 os.walk('c:/Python27') 还是类似的东西?谢谢!
    • 请注意,str.endswith(suffix[, start[, end]]) 可以采用元组作为后缀。过多的“或”比较可能会变得很麻烦。
    【解决方案2】:

    他要求的是平面 readdir,而不是递归文件树遍历。 os.listdir() 完成这项工作。

    【讨论】:

      【解决方案3】:

      用 Python 做吗?否则,只需 grep -l "string" *.txt *.log 即可。

      【讨论】:

      • lbrahim 是的,我需要在 Python 中执行此操作。感谢您的信息!
      • @Andre Caron 这看起来是一个合理的问题......当你能听到文字时,你一定很聪明! ......你是谁来确定它听起来像什么?小伙子,我早就毕业了……这是个人兴趣爱好。没有什么比带来消极情绪更好的了。像你这样的人......
      猜你喜欢
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多