I’ve been working my way through the first book (Learn Python the Hard Way), the HTML version. In reviewing Exercise 20, I noticed something interesting.
The “print_a_line” function that you write as part of the exercise, doesn’t actually work as you might expect.
I started playing with the value of line_count near the end of the program, when you call print_a_line three times, incrementing the counter each time. I found that if I changed line_count so it goes 2, 4, 6, or 3, 7, 17, or even 1, 1, 1 (!), the result is the same.
That is, the three calls to print_a_line always print out the first three lines of the file. The line_count value only affects the line index displayed. f.readline() disregards it completely, it just picks up from the last line end and keeps going.
I tested this by making my own, much longer input text file. It is just 10 lines:
I wrote it that way so it would be easy to see what line was actually being printed.
No I’m wondering whether there’s a way to reference an arbitrary line of a file. That is, jump straight to line 4 without first going through lines 2 and 3.
I’m sure the answer is “yes.” I just haven’t worked out the details yet.
This is fun!