Programs that Keep Their Data

Going through a file line by line

Follow a loop that visits every line of a file in turn, turns each line into a number where it needs to, and leaves a total or a count behind.

A file of a thousand readings is no harder to handle than a file of three, as long as the program never needs to know which of the two it has been given. A loop written "for line in f:" over an opened file makes exactly one trip for each line in it, in the order the lines are stored, and hands over one line each time. Nothing in the program says how many lines there are — the file decides that, which is why the same program works tomorrow when the file has grown.

Every line arrives as writing, with its line break still attached

A line out of a file is writing, even when every character of it is a digit, and it comes with the line break that ended it still on the end. So a total that is meant to add up a file's numbers has to say int(line) rather than line: writing added to writing joins the two together instead of adding them up, and writing added to a number stops the program. The line break is not a problem for int — it quietly ignores the break and any spaces round the number — but it is a problem for anything that compares one piece of writing with another, because a line that looks like red is really red-and-a-line-break.

Worked example

Exactly what does the loop hand over on each trip through this file?

f = open("marks.txt", "w")
f.write("50\n42\n")
f.close()
  1. The file holds two lines. Reading it with a line loop therefore makes two trips, whatever the program does inside them.

    The trips are settled by the file and not by the loop. Nothing in the heading says two.

Try it together

Now a program that saves a dictionary's values into a file.

stock = {"pen": 4, "bag": 9}
f = open("stock.txt", "w")
for name in stock:
    f.write(str(stock[name]) + "\n")
f.close()

The loop runs over a dictionary, and what goes into the file is the result of a lookup rather than the loop variable itself.

    1.How many lines does the file hold once this program has finished?

    Have a go

    Have a go on your own. The whole file is read into a list here rather than looped over. What does the program print?

    f = open("nums.txt", "w")
    f.write("10\n20\n30\n")
    f.close()
    f = open("nums.txt", "r")
    lines = f.readlines()
    f.close()
    print(int(lines[2]) - int(lines[0]))

    Ready to practise?

    Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.

    Print a worksheet