查找并打印包含测试字符串的行

时间:2014-07-29 03:12:58

标签: python regex

我有一个包含以下内容的文本文件(.txt):

Active nodes=225785 elements=171665
Running protocol file all_in_one.prot"
Error reading input protocol file
20 coincident elements
Set 999 created (20 elements)
All 171665 elements are suitable
Error reading input protocol file
No nodes deleted in SHOW
No elements displayed
Active nodes=225785 elements=171665
Structure disintegrates
Set >ECHCON-Decay< consists of 164361 elements

现在我的任务是找出字符串“元素是合适的”,然后如果找到字符串,我需要打印它所在的行。我可以使用re模块吗?

1 个答案:

答案 0 :(得分:2)

是的,但你不需要。

with open('somefile.txt', 'r') as f:
  for line in f:
    if 'elements are suitable' in line:
      print line