Jungle Hunter
Jungle Hunter

Reputation: 7285

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

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()?

Upvotes: 25

Views: 10483

Answers (3)

aaronasterling
aaronasterling

Reputation: 71014

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.

Upvotes: 19

John La Rooy
John La Rooy

Reputation: 304185

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

Upvotes: 16

crdx
crdx

Reputation: 1432

readlines() returns a list of lines, which you may want if you don't plan on iterating through each line.

Upvotes: 1

Related Questions