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

前端 未结 3 750
無奈伤痛
無奈伤痛 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条回答
  •  误落风尘
    2020-12-20 14:45

    Python's file iterator does a lot of buffering, thereby advancing the position in the file far ahead of your iteration. If you want to use file.tell() you must do it "the old way":

    with open(filename) as fileob:
      line = fileob.readline()
      while line:
        print fileob.tell()
        line = fileob.readline()
    

提交回复
热议问题