xreadlines和for-looping一个文件之间的区别 [英] Difference between xreadlines and for-looping a file

查看:163
本文介绍了xreadlines和for-looping一个文件之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.7中有一个文件对象:

  f = open('my_file','r')

循环文件(最常见的方式)和使用 xreadlines()函数:

 用于f:
中的行行

 < code $ for line in f.xreadlines():













$

我的意思是,这两个选项定义了一个生成器,与 readlines() read()函数加载所有的文件内容到内存。

是否有任何性能或文件处理的改进?或者他们只是做同样的事情的等价的方法?

docs.python.org

  file.xreadlines()
此方法返回与iter(f)相同的结果。

版本2.1中的新功能。

从版本2.3开始弃用:代替文件中的行。

...最好使用关键字;

  with open('my_file','r')as f:
for line在f:
#做东西


Having a file object in Python 2.7:

f = open('my_file', 'r')

What would be the difference between for-looping the file (most common way) and using the xreadlines() function:

for line in f:
    # Do something with line

and

for line in f.xreadlines():
    # Do something with line

I mean, both options define a generator, in contrast to the readlines() or read() functions that loads all the file content to memory.

Is there some performance or file-handling improvment in any of them? Or they are just to equivalent ways of doing the same thing?

解决方案

From docs.python.org

file.xreadlines()
This method returns the same thing as iter(f).

New in version 2.1.

Deprecated since version 2.3: Use for line in file instead.

... and it's better to use the with keyword when working with files; again see the docs page.

with open('my_file', 'r') as f:
    for line in f:
        # do stuff

这篇关于xreadlines和for-looping一个文件之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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