How to loop until EOF in Python?

后端 未结 6 483
南笙
南笙 2020-12-08 03:38

I need to loop until I hit the end of a file-like object, but I\'m not finding an \"obvious way to do it\", which makes me suspect I\'m overlooking something, well, obvious.

6条回答
  •  鱼传尺愫
    2020-12-08 04:00

    Have you seen how to iterate over lines in a text file?

    for line in file_obj:
      use(line)
    

    You can do the same thing with your own generator:

    def read_blocks(file_obj, size):
      while True:
        data = file_obj.read(size)
        if not data:
          break
        yield data
    
    for block in read_blocks(file_obj, 4):
      use(block)
    

    See also:

    • file.read

提交回复
热议问题