Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need readlines() when we can iterate over the file handle itself?

Tags:

In Python, after

fh = open('file.txt') 

one may do the following to iterate over lines:

for l in fh:     pass 

Then why do we have fh.readlines()?

like image 602
Jungle Hunter Avatar asked Oct 14 '10 12:10

Jungle Hunter


People also ask

What does file Readlines () do?

The readlines() method returns a list containing each line in the file as a list item. Use the hint parameter to limit the number of lines returned.

How do you iterate through a file in Python?

To iterate through lines in a file using Python, you can loop over each line in a file with a simple for loop. When reading files, the ability to read files sequentially line by line can be very useful. Reading text from a file is easy with the Python open() function.

When reading a file using the file object what method is best for reading the entire file into a single string?

The readlines method returns the contents of the entire file as a list of strings, where each item in the list represents one line of the file. It is also possible to read the entire file into a single string with read .


1 Answers

I would imagine that it's from before files were iterators and is maintained for backwards compatibility. Even for a one-liner, it's totally1 fairly redundant as list(fh) will do the same thing in a more intuitive way. That also gives you the freedom to do set(fh), tuple(fh), etc.

1 See John La Rooy's answer.

like image 119
aaronasterling Avatar answered Nov 09 '22 08:11

aaronasterling