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

Mostly it is there for backward compatibility. readlines was there way before file objects were iterable

Using readlines with the size argument is also one of the fastest ways to read from files because it reads a bunch of data in one hit, but doesn't need to allocate memory for the entire file all at once


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.

Tags:

Python