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
    self.f.write(self.savegame)
    #Close the file
    self.f.close()
    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:
        self.saves.append(line)
      #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: http://docs.python.org/library/re.html
      self.match = re.search(r'(w+s*w*)ss(w+s*w*)ss(d+)', self.saves[0])
      #Now put the groups in the related variables
      name = self.match.group(1)
      weapon = self.match.group(2)
      level = self.match.group(3)
      #Close the file
      self.f.close()`

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
    Option().save()
    print "Saved"
  elif choice == 2:
    Option().load()
    print "Name: " + name
    print "Weapon: " + weapon
    print "Level: " + str(level)
    raw_input()