相对于python中的一行向后读取行

时间:2015-10-02 06:15:43

标签: python python-2.7 python-3.x

我正在使用

逐个循环遍历所有行
line = file.readline() 

现在每行搜索特定字符串(XYZ) -

line.startswith('XYZ')

我无法弄清楚如何找到相对于找到字符串XYZ匹配的行后面的几行。

我知道这可能是微不足道但却无法实现的。

3 个答案:

答案 0 :(得分:3)

您可以使用collections.deque()缓存前两行:

#!/usr/bin/env python
import sys
from collections import deque

cached_lines = deque(maxlen=2) # keep 2 lines
for line in sys.stdin:
    if line.startswith('XYZ'):
        sys.stdout.writelines(cached_lines)
    cached_lines.append(line)

优点是您不需要将整个文件读入内存。

实施例

$ python . <input >output 

输入

XYZ 1
2
3
4
XYZ 5
XYZ 6
7
8
9
XYZ 10
11
12

输出

3
4
4
XYZ 5
8
9

答案 1 :(得分:0)

file.tell()提供当前文件指针。 file.seek(指针)将文件指针设置为给定指针。如下面的代码,

pointer = file.tell()

...

...

...

file.seek(指针)

答案 2 :(得分:0)

您需要保存所有已降级的行或只需使用readlines方法。

lines = file.readlines()
for i in range(0, len(lines)): 
    if lines[i].startswith("XYZ"):
        print lines[i-2]
        print lines[i-1]
相关问题