在iter(fp.readline,'')而不是fp中的行: [英] line in iter(fp.readline, '') rather than line in fp:

查看:324
本文介绍了在iter(fp.readline,'')而不是fp中的行:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 iter 的示例rel =nofollow noreferrer>内置函数 - Python 3.7.0文档

I read builtin function iter 's example in Built-in Functions — Python 3.7.0 documentation

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)

我无法弄清楚以下优势是什么:

I could not figure out what's the advantage over the following:

with open('mydata.txt') as fp:
    for line in fp:
        process_line(line)

你能否提供任何提示?

推荐答案

两者都会迭代生成器,而不会将整个文件加载到内存,但 iter()版本正在演示使用 iter()的第二个参数定点

Both will iterate over a generator, without loading the whole file into memory, but the iter() version is demonstrating the use of the second argument of iter(), "sentinel".

来自文档:


如果返回的值等于sentinel, StopIteration将被提升

if the value returned is equal to sentinel, StopIteration will be raised

所以此代码将从文件中读取,直到一行等于''然后停止。

So this code will read from the file, until a line equals '' and then stop.

这是一个奇怪的例子,因为文件中的所有行都会在末尾有换行符,所以这只会在文件末尾触发(如果在所有)。

This is a strange example, as all lines in the file will have a newline on the end, so this will only trigger at the end of the file anyway (if at all).

这篇关于在iter(fp.readline,'')而不是fp中的行:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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