简体   繁体   English

在文件中迭代 for 时向后移动

[英]move backwards when iterate a for in a file

imagine this situation:想象一下这种情况:

a file with 1000 lines.一个有 1000 行的文件。 the name of the file is file.txt文件名是file.txt

file = file.txt
word = 'error'
for line in file:
    if word in line:
        execute things

if I want the 8 lines BEFORE the line with the word "error", how I get it?如果我想要在带有“错误”一词的行之前的 8 行,我如何得到它?

Read the file and save the lines in a deque of a fixed size读取文件并将行保存在固定大小的deque

from collections import deque

file = "file.txt"
word = 'error'

lines = deque(maxlen=8)
with open(file) as f:
    for line in f:
        if word in line:
            break
        lines.append(line)

print(lines)

You can use combination of collections.deque() with fixed length and itertools.takewhile() .您可以使用固定长度的collections.deque()itertools.takewhile()的组合。

from collections import deque
from itertools import takewhile

with open("file.txt") as f:
    lines = deque(takewhile(lambda l: "error" not in l, f), maxlen=8)
print(*lines, sep="", end="")

You can help my country, check my profile info .你可以帮助我的国家,查看我的个人资料信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM