2

I'm using Python 2.7.8 and I'm trying to code a simple text-based game. In order for it to work well, I'd like to be able to save certain variables into a text file and then load them back in as variables the next time I run the program. Ideally, I'd like to store each variable on its own line but I'm not quite sure how to make that happen. EDIT: Here's my relevant code:

https://gist.github.com/anonymous/3a14fcd68b0045b2c0c0

For some reason, the code crashes at launch. Apologies because I'm a little new to Python. Anyway, is there a better way to write this information to a file? In addition, what could I use to read a variable from that file and store it as a variable in the game?

EDIT: I have now learned something incredibly useful which allows me to debug. Here is what the shell says when the code is run:

https://gist.github.com/anonymous/bfc085d8d1d0b7969574

Thanks so much.

5
  • 1
    Have a look at the ConfigParser examples entry in the Python wiki - should be exactly what you need. Commented Sep 2, 2014 at 4:11
  • Please forgive me, but I'm not sure if I understand how this works. Here's my code: #setting up save file savefile = "C:\Users\Slick\Documents\python\save.ini" FILE = open(savefile,"w") Config.add_section('info') countryname = raw_input("What will your country be called? ") print "Welcome to " + countryname + "!" time.sleep(0.5) Config.set('info','name',countryname) Config.write(savefile) At the end, I also have: FILE.close() The file crashes at launch. What am I doing wrong? Commented Sep 2, 2014 at 4:36
  • It may just be that I'm viewing this on a mobile browser, but the indentation in the code doesn't look right at all. Commented Sep 2, 2014 at 5:25
  • @AlexThomas - please don't put code in comments. Commented Sep 2, 2014 at 6:17
  • @AlexThomas: for the UnboundLocalError: local variable 'countryname' referenced before assignment, if I say "y" to the question on line 29, it's going to execute lines 31-35, which don't define countryname, then it's going to skip down to line 54, where it tries to use countryname. You need to add code to the block on line 31-35 to set countryname. Also, the code is still a bit off in the pastebin (see line 39, I don't think you want that line there). Commented Sep 2, 2014 at 16:28

3 Answers 3

3

Using the ConfigParser example you create your "save file" like this:

import ConfigParser

countryName = raw_input("What will your country be called? ")

config = ConfigParser.RawConfigParser()

config.add_section('Countries')
config.set('Countries', 'MyCountry', countryName)

with open('save.txt', 'wb') as saveFile:
    config.write(saveFile)

Running this will create a "save.txt" file which you can then read using:

import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('save.txt')

countryName = config.get('Countries', 'MyCountry')
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this solution and after some implementation errors, I was finally able to get it to work. I'm selecting this as my accepted answer, but one more question, if I may: is there a way to put each variable on its own line within the text file?
adding further config.set("section", "variableNameToStore", variableInCode) lines should store them in your "save file" on separate lines. Is this what you need or am I missing something?
Yes, that is what I need, though the data is not being stored on separate lines. If you need to see my code then I can show you but it's pretty much exactly what you have here with the addition of another config.set for testing.
2

The most robust answer to this problem is to pickle the data that you want to store: https://docs.python.org/2/library/pickle.html

Roughly speaking, Pickle takes an object and turns it into a string. You can later "unpickle" the string to get the object back out.

Pickling may be too complex a solution for you if your data is simple and you want to be able to view and modify it by hand. One possibility that I would strongly recommend in this case is to use XML or JSON as a data storage format. These have the flexibility to represent structures like hashtables and lists, which simpler formats (including most formats that you might define yourself) would lack.

Comments

0

There are a bunch of ways to do this! ConfigParser, shelve, sqlite, pickle, etc.

I would do something really simple to start. For example, create two functions "get_value(name)" and "set_value(name, value)" like this:

import os
import time

#######

def get_value(name):
    name += '.cfg'
    if not os.path.exists(name):
        return ''
    with open(name) as f:
        return f.read()

def set_value(name, value):
    name += '.cfg'
    with open(name, 'w') as f:
        f.write(value)

#######

if __name__ == "__main__":
    countryname = get_value('countryname')
    if not countryname:
        countryname = raw_input("What will your country be called? ")
        set_value('countryname', countryname)

    print "Welcome to %s!" % countryname
    time.sleep(0.5)

This will create one file per value. If that gets too unwieldy I would switch to JSON.

Here it is in action:

$ python game.py
What will your country be called? Steveland
Welcome to Steveland!

# it remembers my answer
$ python game.py
Welcome to Steveland!

$ ls *.cfg
countryname.cfg

# reset my answer
$ rm countryname.cfg

$ python game.py
What will your country be called? Stevesylvania
Welcome to Stevesylvania!

3 Comments

This solution seems to be the most understandable to me, but it won't work and I have no idea why. Once again, I apologize for being such a noob. x) I typed in that code almost exactly (where it belonged in the file) but the game simply crashes on launch again. Scanned for typos and found nothing. I'll edit the original post with more of the game's code, hopefully that will clear things up.
@AlexThomas I don't see anything in the question about crashing on launch. Please edit it to include the traceback and any other relevant details.
@AlexThomas Please post the traceback so we can help you debug. I notice in the code you've updated the indentation is off a bit. Maybe you can put your code on a pastebin? Like gist.github.com

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.