Start New Discussion within our Software Development Community

Is there any way to save to progress of a Python Program onto an I.P. Address or Harddrive? Like if you enter '5' into a program that multiplies your number by 3 and save it, your saved number would be 'x' when you reopen the file. I need help! :)

Yeah there sure is

#use the current directory or absolute path
f = open("File.txt",'w')    #write mode 'w'
answer = 5*3
#make a string, only stings can be added to files
answer = str(answer) 

#then open it back up
o = open("File.txt",'r')  #read mode 'r'
print o.readline()

I have a solution which allows you to use a persistent dictionary between different excecutions of your program, using the with statement (python >= 2.5). Here is an exemple program:

from __future__ import with_statement
from persistent import PersistentDict

def main(pdict):
    if not 'x' in pdict:
        pdict['x'] = 0
    pdict['x'] += 1

with PersistentDict("persistent.pkl") as pdict:

And here is the module "" which makes this possible

# -*-coding: iso8859-1-*-   
""" - module for persistence -
    Allows python programs to use a persistent dictionary between executions.

        from __future__ import with_statement
        from persistent import PersistentDict

        def main(pdict):
            # Your pogram's code goes here
        with PersistentDict("myfile.pkl") as pdict:
    import cPickle as pickle                       
except ImportError:                                
    # python 3.0
    import pickle

class PersistentDict(object):
    def __init__(self, path):
        self.path = path
        self.pdict = None
    def __enter__(self):
            file_in = open(self.path)
            self.pdict = pickle.load(file_in)
        except IOError:
            self.pdict = dict()
        return self.pdict
    def __exit__(self, *args):
        file_out = open(self.path, "w")
        pickle.dump(self.pdict, file_out)
        self.pdict = None

This module could easily be extended to support persistent lists or more general persistent objects. If everybody likes it, I'll put it in the python code snippets :)

Okay so how can I convert that into saving a whole load of info? See my Python Game: NorbertQuest thread because the game's what I want to save.

You can use pickle, that is useful because it saves the data as it is, so if you have a class you can save the class, and then you load it and it is exactly the same as it was when you saved it.

For that you would need to change norbert quest to a class, that shouldn't take too long.

The module you need is Pickle or shelve, google them if you havent used them before

class NorbertQuest(object):
    #every function goes in here
    #every variable is renamed self.variable
    #so if i was "health" it would be ""
   #then you can get rid of all the global this and global that
    #because using "self" means that is can be accessed all over the class

n  = NorbertQuest()

pickles good for 1 time writing but i would recommend pprint as it allows you too write into a file several times, the only problem is that you start again when you re-open it, search for 'phonebook' in the python forum for an example (i needed help with it)

This article has been dead for over six months. Start a new discussion instead.