【问题标题】:python - Read sections of a log filepython - 读取日志文件的部分
【发布时间】:2017-05-17 01:02:21
【问题描述】:

我的日志文件如下所示:

-------------
name=ABC
age=12
DOB=02/12/2001
EOL
-------------
name=DEF
age=9
DOB=06/20/2005
EOL
-------------
name=XYZ
age=23
DOB=02/12/1992
EOL

如何一次读取一个部分的文件?即从“---”到“EOL”。

【问题讨论】:

标签: python file file-handling sections


【解决方案1】:

这是一个用您的输入(粘贴到“input.txt”)经过实战测试的 Python 示例:

 sections = []

 with open("input.txt") as file:
     section = ""
     for line in file.readlines():
         if line.strip() == "-------------":
             sections.append(section)
             section = ""
         else:
             section += line + "\n"
        print(sections)

现在您可以遍历 sections 列表并对每个集合做任何您想做的事情

【讨论】:

  • 谢谢!以及如何使用正则表达式匹配从每个部分中提取名称和其他详细信息?
  • 您可以遍历sectionif section.startswith('name'): <process name> 中的每一行。为每个属性执行此操作。
猜你喜欢
  • 1970-01-01
  • 2019-08-06
  • 2021-06-22
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
相关资源
最近更新 更多