在用python读取文件时,我想知道如何在遇到符合我条件的行时获取下n
行。
假设有这样的文件
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
现在,每当我们找到以芒果开头的一行时,我希望能够阅读接下来的所有 4 行。
我能够找出如何做下一个直线,但不能做下一个n
直线
if (line.startswith("mangoes:")):
print(next(ifile)) #where ifile is the input file being iterated over
重复你所做的
if (line.startswith("mangoes:")):
for i in range(n):
print(next(ifile))
除非它是一个大文件,并且您不想一次将所有行读取到内存中,否则您可以执行以下操作
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]
这将为您提供n
行数的列表,包括单词mangoes
. 如果您这样做idx=idx+1
那么您也将跳过标题。
具有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))
从输入示例中,生成的mango_lines
列表为:
['1 2 3 4 n', '5 6 7 8n', '8 9 0 7n', '7 6 8 0n']