How to loop until EOF in Python?

后端 未结 6 480
南笙
南笙 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:16

    I prefer the already mentioned iterator-based solution to turn this into a for-loop. Another solution written directly is Knuth's "loop-and-a-half"

    while 1:
        len_name = data.read(4)
        if not len_name:
            break
        names.append(data.read(len_name))
    

    You can see by comparison how that's easily hoisted into its own generator and used as a for-loop.

提交回复
热议问题