Menu

File Handling

Reading every line from a text file

When you do not know how many lines a text file holds, you need a loop that keeps going until the file runs out. In Python, readline() returns an empty string "" once there is nothing left to read, so you can test for that.

Reading until the file runs out

The pattern is: read the first line before the loop, loop while the line is not empty, and read the next line at the end of every pass. A while loop does not move through a file by itself, so without that final readline() the same line would be tested for ever and the loop would never finish.

A blank line partway through a file does not signal the end of the file: it still contains a newline character, so the variable holding the line holds "\n" rather than "", and the loop keeps going. An empty file works too, because the first read returns "" straight away and the loop body never runs.

If you know the file holds exactly four lines, you can call readline() four times, or use a for loop with range(4). Use the end-of-file loop when the file might be shorter or longer than you expect.

Casting and storing the data

Everything read from a text file arrives as a string, even when it looks like a number. Cast it with int() or float() before doing arithmetic; the newline at the end does not stop float() working. Each cast value can be appended to an array, so the data is still available after close(), and added to a running total while you are there.

For example, a file of rainfall readings holds "2.5\n", "4.0\n" and "0.5\n". Following the pattern, one call is made before the loop and one at the end of every pass:

readline() callvalue of the lineline != ""?action
1"2.5\n"Truecast to 2.5, append, add to total
2"4.0\n"Truecast to 4.0, append, add to total
3"0.5\n"Truecast to 0.5, append, add to total
4""Falseloop stops

Practise this