Programs that Keep Their Data
Writing and reading a file
Follow a program that saves writing into a file and reads it back, and work out what the file holds at each point.
Everything a program has kept in its variables is gone the moment it stops. That is fine for a calculation and useless for anything a person wants back tomorrow, which is what files are for. A program opens a file by name, saying at the same time what it means to do with it: "w" for writing and "r" for reading. Then it writes or reads, and then it closes the file, which is the program saying it has finished — until a file is closed there is no promise that what was written has actually reached it. Reading gives back writing, never numbers: a file holding 12 hands back the two characters 1 and 2, and int is what turns that into a number that can be added to something. Going the other way, str turns a number into writing so that it can be written into a file at all.
Opening for writing empties the file first
This is the one that costs people work they had already done. Opening a file with "w" does not put your writing after what is already there — it empties the file at the moment it opens it, before a single write has run. So a program that opens a file with "w", and then decides it has nothing to say and closes it again, has still destroyed everything that was in it. Opening with "r" changes nothing and can be done as often as you like; it is opening for writing that is the dangerous half, and it is dangerous straight away rather than when the writing happens.
Worked example
One file, two ways of reading it. What does each of the two lines give back?
f = open("pets.txt", "w")
f.write("cat\ndog\n")
f.close()The file now holds two lines: cat, then dog. The \n marks are not extra lines — each one is the end of the line it sits on.
A file is really one long run of characters, and the line breaks in it are characters too. Everything about lines comes from where those marks are.
Try it together
Now a program that saves a list of numbers into a file, one number to a line.
marks = [8, 3, 6]
f = open("marks.txt", "w")
for m in marks:
f.write(str(m) + "\n")
f.close()Only the writing line is indented under the loop, so opening and closing happen once each, whatever the loop does.
1.How many times does the writing line run?
Have a go
Have a go on your own. Nothing is read back this time — how many lines does the file hold when this program has finished?
f = open("notes.txt", "w")
f.write("a note\n")
f.write("and another\n")
f.write("and one more\n")
f.close()Ready to practise?
Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.