Rohan Prabhu
Rohan Prabhu

Reputation: 7302

readline on a gzip file results in an infinite loop [python]

I have a gzip file and I'm trying to read the lines of the file:

g = gzip.open(filename)

while True:
    dline = g.readline()

    if not dline:
        print "<<" + dline + ">>"

g.close()

The output of the above is:

<<>>
<<>>
<<>>
<<>>
... infinitely

What is wrong here? P.S. The gzip is of a utf-8 text file.

Upvotes: 1

Views: 1650

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 993015

You have no condition that can possibly exit your loop. Try:

while True:
    dline = g.readline()
    if not dline:
        break
    print "<<" + dline + ">>"

The readline() family of functions returns an empty string when there are no more lines to read.

Upvotes: 3

Related Questions