- The simplest thing you might need to do with files is to load or save a single item of data
- The example below uses a text file called savedfile.txt to read/write a number
- The program will produce an error if it does not exist so create it first (in the same directory where your program is saved)
#Open file for reading, read the contents
#of the file and close
file = open(“savedfile.txt”,“r”)
value = file.read()
file.close()
#Print the value from the file
print(value)
#Open file for writing, Write 37 to
#the file and close
file = open(“savedfile.txt”,“w”)
file.write("37")
file.close()

Tasks
- Type in the code to test it works
- Modify the code to accept user input of a new number to save
- Try saving and loading strings, does it work?
- Save and label your code
Extension Task
This technique was how early website counters worked. Each time the code ran, it loads the number from the file, adds 1 and saves it back to the file. Can you implement this technique?