from itertools import groupby
with open('input.txt') as f_input:
for k, g in groupby(f_input, lambda x: x != '\n'):
if k:
print [line.strip() for line in g]
from itertools import islice
with open('input') as f:
while True:
lines = [line.strip() for line in islice(f, 4) if line.strip()]
if not lines:
break
print(lines) # or otherwise process them
您可以使用Python的^{} 函数来读取行,直到找到一个空行,如下所示:
然后将每三行作为一个块读取。如果有多余的空行,这些也会被跳过,或者如果一个块中有三行以上的空行,这些也会被作为单个块读取
这将打印以下内容:
您可以使用
itertools.islice()
一次读取4行文件,如果最后一行是换行符,则将其丢弃:演示
使用此输入:
输出为
这也处理了文件结束时没有一组完整的3行的情况
相关问题 更多 >
编程相关推荐