AQA Computer Science GCSE
Programming projects - File Handling
Saving a text file
To save data in a text file, you need to know how to write that data to the file. This lets you use it again once you've closed the program.
To work through what's going on here, you'll need to download a copy of the highscores text file. Make sure it's saved in the same folders as your Python program.
Open the text file up to check what's in it before you start - stuff will change!
Highscores text file - right click and Save As
Writing to a simple text file
To write to a file in Python, it first needs to be opened, this time using the switch "w" to open it in write mode.
dataToWrite = "Sally Shark, 120"
myFile = open("highscores.txt", "w")
myFile.write(dataToWrite)
myFile.close()
Note that when you run this program in Python, nothing will appear to happen on screen. If you want to you can add a line at the bottom to confirm that the program actually ran:
To see the new contents of the text file you need to open the text file. Make sure you do this, because something odd happened...
Hmm, we have another problem Houston
When the file is written it will overwrite the existing file, replacing it with just the new text (in the example, "Sally Shark, 120").
To solve this problem the technique to use is:
- open the file and read the contents in
- add the new data to the contents using concatenation
- close the open file
- open the file again and write the new, combined data to it
- and close the open file again
At this point you might want to save a new copy of the High Scores text file - because you just destroyed the old one!
This process can be implemented using this code:
myFile = open("highscores.txt", "r")
scores = myFile.read()
myFile.close()
# add the new data to the scores variable
scores = scores + "Sally Shark, 120"
# write the data to the file
myFile = open("highscores.txt", "w")
myFile.write(scores)
myFile.close()
Again, the program won't appear to do anything on screen when you run it.
Now, inspect the text file again. There's another problem: the data got added to the end of the last line of the text file rather than on it's own line.
You can check exactly what happens by reading the file in again using:
myFile = open("highscores.txt", "r")
newscores = myFile.read()
myFile.close()
print(newscores) # print the scores
You could, of course, use the more complex readline method to create an array (list) and then handle that as shown on the reading lists page.
Solving the line break problem
You can solve the line break problem easily enough by using a switch code.
Just replace the line:
scores = scores + "Sally Shark, 120"
with:
scores = scores + "\nSally Shark, 120"
You should be able to figure out what the \n switch does.
You can use \n in a print statement as well if you want to:
print("What is the best way\nto split text over\nmore than one line?")