如何循环直到Python中的EOF? [英] How to loop until EOF in Python?

查看:218
本文介绍了如何循环直到Python中的EOF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要循环播放直到碰到类似文件的对象的末尾,但是我找不到显而易见的方法,这使我怀疑自己正在忽略某些东西,很明显。 :-)

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. :-)

我有一个流(在这种情况下,它是一个StringIO对象,但我也对一般情况感到好奇),该流存储了未知数量的以< length>< data>格式记录,例如:

I have a stream (in this case, it's a StringIO object, but I'm curious about the general case as well) which stores an unknown number of records in "<length><data>" format, e.g.:

data = StringIO("\x07\x00\x00\x00foobar\x00\x04\x00\x00\x00baz\x00")

现在,我能想象到的唯一清晰的方法是使用(我认为是)初始化循环,这似乎有点不符合Pythonic:

Now, the only clear way I can imagine to read this is using (what I think of as) an initialized loop, which seems a little un-Pythonic:

len_name = data.read(4)

while len_name != "":
    len_name = struct.unpack("<I", len_name)[0]
    names.append(data.read(len_name))

    len_name = data.read(4)

在类似C的语言中,我只是将 read(4)放在 while 的test子句,但当然不适用于Python。对实现此目标的更好方法有任何想法吗?

In a C-like language, I'd just stick the read(4) in the while's test clause, but of course that won't work for Python. Any thoughts on a better way to accomplish this?

推荐答案

您可以通过 iter()和前哨:

for block in iter(lambda: file_obj.read(4), ""):
  use(block)

这篇关于如何循环直到Python中的EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆