可能重复:一次
读取2行
在python中,我们可以逐行迭代文件.但是,如果我想要两行迭代怎么办?
f = open("filename")
for line1, line2 in ?? f ??:
do_stuff(line1, line2)
Run Code Online (Sandbox Code Playgroud)
使用itertools配方中的grouper函数.
from itertools import zip_longest
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
f = open(filename)
for line1, line2 in grouper(2, f):
print('A:', line1, 'B:', line2)
Run Code Online (Sandbox Code Playgroud)
使用zip而不是zip_longest忽略末尾的奇数行.
该zip_longest函数izip_longest在Python 2 中命名.
你可以这样做:
with open('myFile.txt') as fh:
for line1 in fh:
line2 = next(fh)
# Code here can use line1 and line2.
Run Code Online (Sandbox Code Playgroud)
如果您有奇数线路,您可能需要注意StopIteration调用时是否出现错误next(fh)。解决方案izip_longest可能能够更好地避免这种需求。