That Blue Square Thing

AQA Computer Science GCSE

Programming projects - File Handling

When a program is running, data is stored in variables (named areas of memory where a single value can be stored). When the program stops, the data is lost.

To keep data when a program is closed you need to save it in a text file. To do this you need to know how to open, read, write and close files. This process is known as file handling.

Note that file handling is a slightly complex process and a whole set of problems can occur. The good news is that it no longer forms part of the Paper 1 exam. But if you're doing anything complex in Python it's a handy thing to be able to do.

Text file

File read/write in Python uses text files. To follow the examples below you'll need the highscores text file below.

Text file iconHighscores text file - right click and Save As

You need to make sure you save the highscores.txt file in the same folder as your Python files. This is crucial. If the files are saved somewhere else then the programs won't work!

Reading a simple file

To read from a file in Python it first needs to be opened, using the switch "r" to open it in read mode. The file is then read and the data in it stored in a variable - in the example I use a variable called scores. Then you close the file.

# readfile program
myFile = open("highscores.txt", "r")
scores = # assign data in file to variable

Note that the data in the text file is stored as a string at this stage. There are more complex ways to save data using arrays (lists), but we'll keep it simple to begin with.

The variable myFile is used as a temporary name for the contents of the opened text file. It's closed once you finish reading in the contents.

It is really important to make sure that the text file is closed at the end of the process. All sorts of problems can, theoretically at least, occur if the file isn't closed properly, so really take care with this.

Houston, we have a problem

This method reads the file in as a single string variable. So, all three are stored in one named area of memory - complete with the line breaks. So when you print it, it looks like three separate bits of data. But it's not.

Sometimes that can be exactly what you want, but the chances are that a lot of the time you might need to store each individual's high score in a separate variable so that you can use them sensibly.

To learn how to do that, go on to Reading Simple Lists.

If you'r ready to find out how to save your own text files, go on to the Writing Files page.