Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

I find a funny things in readline() method:

a file name '123' which contain:'1. first line\n2. second line\n3. third line' so right now when I input these code:

a = open('123','r')
while a.readline() != '':
    print(a.readline())
## the result will always only print 2.second line\n 
## so I suspect if because when I use a.readline(), I don't give him a variable name, so I change the code into this:
a = open('123','r')
b = a.readline()
while b != '':
    print(b)
# when I test the obove code ,there is loop infinit, so I guess that is because b is the first line which is '1.first line', so even ## the loop, so it still b.
## But when I do this code:
a = open('123','r')
b = a.readline()
c = a.readline()
d = a.readline()
e = a.readline() 
# b = '1. first line\n' , c = '2. second line\n' , d = '3. third line', e = '' 

so I don't know why does those things happened. I don't know why , thank you for help me.

[MOD: edited code block]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

In your code, the first example consumes a line during the while test, so the print will see line 2 first. The second example b is assigned outside of the loop so its value does not change causing an infinite loop.

From the python docs 'iter' has a solution

for line in iter(a.readline, ''):
    print(line)

Or use in:

a = open("123", 'r')
for line in a:
    print(line)

Thank you point to me. Right now I know what does the loop head real do. Each time the loop head will proceed first. After will loop. Before I only learn how to loop, but never deeply think of that, thank you very much.