Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between xreadlines and for-looping a file

Tags:

python

file

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?

like image 884
juliomalegria Avatar asked Dec 18 '11 23:12

juliomalegria


1 Answers

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
like image 150
Fredrik Pihl Avatar answered Oct 11 '22 15:10

Fredrik Pihl