在Python中匹配文本后打印第N行

3

我想在每次搜索匹配后打印文本文件中的第13行。这意味着每次在文本文件中找到搜索模式时,它都应该打印出接下来的第13行。

我现在正在使用的代码仅打印与搜索匹配的当前行。有人能帮我如何打印每个匹配后的第13行吗?

import sys
import re
com=str(sys.argv[1])
with open("/tmp/sample.txt", 'r') as f:
    for line in f:
          if com in line:
            print (line)
1个回答

4

最简单的方法是一次性读取所有行,然后搜索并打印:

import sys
import re
com=str(sys.argv[1])
with open("/tmp/sample.txt", 'r') as f:
    lines = f.readlines()
    for index, line in enumerate(lines):
        if com in line:
            print lines[index+13]

假设,当然,如果还有一行可以在下面打印13行... 否则,您可以添加:
        ....
        if com in line:
            try:
                print lines[index+13]
            except IndexError:
                pass  # or whatever you want to do.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接