python - 如何在文件中获取目标行及其特定的上一行?
我需要在一些输出结果中找到某一行。我可以做到这一点,但在找到正确的输出部分后,我还需要提取在那一行之前的某些行。
for i, line in enumerate(lines):
target = str(self.ma3) # set target string
if target in line:
print i, line # this gets the correct line, I can stick it in a variable and do stuff with it
i = i - 4 # now I want the line 4 lines before the initial target line
print lines[i] # doesn't work, gives error: TypeError: 'generator' object has no attribute '__getitem__'
如果有人知道怎么做,帮忙就太感谢了!
2 个回答
1
我同意关于使用列表(lines)的回答。这是最简单的解决方案。
不过,如果你的输入文件太大,而且你想使用生成器的话,可以使用collections.deque来保存最后4行,以防你需要用到它们。随着你继续处理,旧的行会被丢弃。
from collections import deque
mybuffer = deque(maxlen=4)
for i, line in enumerate(lines):
mybuffer.append(line)
#...some more of your code...
if target in line:
line_4_lines_before = mybuffer[0]
line_3_lines_before = mybuffer[1]
5
你需要用列表来实现随机访问:
lines = list(lines)
# your code
生成器一次只给你一个项目,它没有“索引”的概念,这和列表不一样。
另外,如果你的文件非常大,把所有行都放进列表里可能会消耗太多资源,你可以选择一次从生成器中提取4个项目。这样的话,当你找到目标行时,你就可以访问到它之前的四行。你需要做一些记录,以确保不会漏掉任何行。