[英]How to get next n lines from in a file when a line is found
While reading a file in python, I was wondering how to get the next n
lines when we encounter a line that meets my condition.在读取 python 中的文件时,我想知道当遇到符合我条件的行时如何获取下
n
行。
Say there is a file like this说有这样的文件
mangoes:
1 2 3 4
5 6 7 8
8 9 0 7
7 6 8 0
apples:
1 2 3 4
8 9 0 9
Now whenever we find a line starting with mangoes, I want to be able to read all the next 4 lines.现在,每当我们找到以芒果开头的一行时,我都希望能够阅读接下来的所有 4 行。
I was able to find out how to do the next immediate line but not next n
immediate lines我能够找出如何做下一个直接行,但不是下
n
直接行
if (line.startswith("mangoes:")):
print(next(ifile)) #where ifile is the input file being iterated over
just repeat what you did重复你所做的
if (line.startswith("mangoes:")):
for i in range(n):
print(next(ifile))
Unless it's a huge file and you don't want to read all lines into memory at once you could do something like this除非它是一个巨大的文件并且你不想一次将所有行读入 memory 你可以做这样的事情
n = 4
with open(fn) as f:
lines = f.readlines()
for idx, ln in enumerate(lines):
if ln.startswith("mangoes"):
break
mangoes = lines[idx:idx+n]
This would give you a list of the n
number of lines, including the word mangoes
.这将为您提供
n
行的列表,包括单词mangoes
。 if you did idx=idx+1
then you'd skip the title too.如果你做了
idx=idx+1
那么你也会跳过标题。
With itertools.islice
feature:使用
itertools.islice
功能:
from itertools import islice
with open('yourfile') as ifile:
n = 4
for line in ifile:
if line.startswith('mangoes:'):
mango_lines = list(islice(ifile, n))
From your input sample the resulting mango_lines
list would be:从您的输入样本中,生成的
mango_lines
列表将是:
['1 2 3 4 \n', '5 6 7 8\n', '8 9 0 7\n', '7 6 8 0\n']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.