PyTAG: Saving and Loading

Mon, Sep 5, 2011 2-minute read

This is another of my “Python Text Adventure Game” tutorials. I’ll show you a simple way to save data to a file and load it again.

First of all, you have to import the regular expression module re.

import re

Now set some variables:

name = raw_input("Your name: ")
weapon = raw_input("Your weapon: ")
level = raw_input("Your level: ")

Now you need a class with the save and load functions:

class Option:
  #The function to save your current data
  def save(self):
    #Open the file or create it if it does not exist<br />
    self.f = open('saves.txt', 'w+')
    #Put everything you want to save in a single variable and use two spaces as a separator
    #It would look like this: Username  5  Sword
    self.savegame = name + "  " + weapon + "  " + str(level)
    #Now write it into the file. this will overwrite any existing save
    #Close the file
    def load(self):
      #Open the file
      self.f = open('saves.txt', 'r')
      #Create a list for the saves
      self.saves = []
      #Add each line to the list and count up
      for line in self.f:
      #We are assuming that there is only one savegame and that it is in the first line
      #Now we use the imported re module to search the content of the file for a pattern and group it
      #You can find more infos about it here:
      self.match ='(w+s*w*)ss(w+s*w*)ss(d+)', self.saves[0])
      #Now put the groups in the related variables
      name =
      weapon =
      level =
      #Close the file

Add this code to test everything:

loop = 1
while loop == 1:
  print "What do you want to test?"
  print "1) Save"
  print "2) Load"
  choice = int(raw_input())
  if choice == 1:
    # Create some variables
    print "Saved"
  elif choice == 2:
    print "Name: " + name
    print "Weapon: " + weapon
    print "Level: " + str(level)