Python: rewinding one line in file when iterating with f.next()

前端 未结 3 753
無奈伤痛
無奈伤痛 2020-12-20 14:23

Python\'s f.tell doesn\'t work as I expected when you iterate over a file with f.next():

>>> f=open(\".bash_profile\", \"r\")
>>> f.tell()
         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 14:47

    itertools.tee is probably the least-bad approach -- you can't "defeat" the buffering done by iterating on the file (nor would you want to: the performance effects would be terrible), so keeping two iterators, one "one step behind" the other, seems the soundest solution to me.

    import itertools as it
    
    with open('a.txt') as f:
      f1, f2 = it.tee(f)
      f2 = it.chain([None], f2)
      for thisline, prevline in it.izip(f1, f2):
        ...
    

提交回复
热议问题