Reputation: 15
How is this while loop working?
myfile = open(r'E:\poem.txt',"r")
str=" "
while str:
str = myfile.readline()
print(str,end=" ")
myfile.close()
Upvotes: 0
Views: 84
Reputation: 1649
myfile.readline()
returns an empty string in case it has no more lines to read from the file. This is the only case in which it returns this value. Therefore, one can use it as a boolean condition in while
or if
statements.
Hence, in the example above, the while
loop stops when there are no more lines to read.
See this post for further information.
Upvotes: 2
Reputation: 765
I don't think it's the best solution. Here's a more pythonic one:
with open(r'E:\poem.txt') as myfile:
for line in myfile:
print(line, end=' ')
with
statement will automatically close the file for you.
Upvotes: 1