41. Read/Write A Single Value

  • 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

  1. Type in the code to test it works
  2. Modify the code to accept user input of a new number to save
  3. Try saving and loading strings, does it work?
  4. 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?