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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With