reading lines 2 at a time

前端 未结 3 2136
野趣味
野趣味 2020-12-07 01:11

Is there a better way to read lines two at a time from a file in python than:

with open(fn) as f:
    for line in f:
        try:
            line2 = f.next(         


        
3条回答
  •  有刺的猬
    2020-12-07 01:23

    You could possibly make it more clear with a generator:

    def read2(f):
        for line in f:
            try:
                line2 = f.next()
            except StopIteration:
                line2 = ''
    
            yield line, line2
    
    with open(fn) as f:
        for line1, line2 in read2(f):
            print line1
            print line2
    

提交回复
热议问题