Heuyie
Heuyie

Reputation: 97

When is a good time to use readline()?

Many have asked how to read a file line by line in Python. And, instead of using readline(), many have recommended the following way:

with open('myfile.py') as f:
  for line in f:

Also, some said that readlines() is not an efficient way to use memory because it reads everything at once.

Is there any time that I should use readline() over the recommended method above? Or, should I forget about this function??

Upvotes: 1

Views: 364

Answers (2)

Michael Butscher
Michael Butscher

Reputation: 10959

You should use readline() only if using for is not possible or useful.

Example: The file contains a fixed header like

  • 1st line: Fixed identification string of file type
  • 2nd line: filetype version identifier
  • 3rd line: Size of following binary data
  • Followed by: binary data of given amount

In such a case a for-loop would need some kind of line count variable to remember which line is currently processed.

This would end up in code like this:

for i, line in enumerate(f):
    if i == 0:
        if line != "Foobar file format\n":
            raise Exception("Wrong file format")
    elif i == 1:
        if int(line) > 4:
            raise Exception("File format version too new")
    elif i == 2:
        size = int(line)
        break

instead of simply this

if f.readline() != "Foobar file format\n":
    raise Exception("Wrong file format")

if int(f.readline()) > 4:
    raise Exception("File format version too new")

size = int(f.readline())

(some error checks omitted for clarity)

Upvotes: 2

wjmccann
wjmccann

Reputation: 522

Readlines could be useful if you want to use each of the lines, one at a time, but not in the order that they appear inside of the file (ie, line 3->2->6->5->etc.).

Upvotes: 1

Related Questions