MSaudi
MSaudi

Reputation: 4652

Correct condition for file reading using readline() in Python

I understand the code below works fine. Reading the while loop documentation in Python, they say that while expression should be True or False and that makes sense.

Now the readline() function returns string. So how this while loop works that way?

with open(datafile, "r") as f:
        line = f.readline();
        while line :
            print line
            line = f.readline()
            data.append(line)
        print line
    return data

Upvotes: 2

Views: 358

Answers (2)

John Stark
John Stark

Reputation: 1297

A string in Python that is equal to "" evaluates to False, while any string that is not blank will evaluate to True.

#Evaluates to False
print(bool(""))

#Evaluates to True
print(bool("A String"))

In the loop you have specified, if there was a line that was successfully read, the string line will not be blank, and thus will evaluate to True. Once there is a line that didn't read in a string, the string line will be set to False and the loop should exit.

Upvotes: 0

cdarke
cdarke

Reputation: 44364

When used in a boolean context, many objects resolve to True or False, in this case that includes an empty string. Numeric zero, an empty tuple, list, set, and dictionary are also False.

A class can decide itself when/if an object is True or False by providing a __bool__ method (or __nonzero__ in Python 2). Although sometimes truth is not relevant for an object.

See also Defining "boolness" of a class in python

Upvotes: 2

Related Questions