我正在寻找 Python 中的一种方法,它可以从文件中读取多行(一次 10 行)。我已经研究过 readlines(sizehint)
,我试图传递值 10 但不只读取 10 行。它实际上一直读取到文件末尾(我试过小文件)。每行长 11 个字节,每次读取应该每次获取 10 行。如果找到的行少于 10 行,则只返回这些行。我的实际文件包含超过 15 万行。
知道如何实现吗?
最佳答案
您正在寻找 itertools.islice()
:
with open('data.txt') as f:
lines = []
while True:
line = list(islice(f, 10)) #islice returns an iterator ,so you convert it to list here.
if line:
#do something with current set of <=10 lines here
lines.append(line) # may be store it
else:
break
print lines
关于python - 在 Python 中读取多行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12790983/