1.11M Members

Saving in Python

 
0
 

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! :)

 
0
 

Oh snap I accidentally typed 'x' instead of 15, sorry folks.

 
0
 

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) 
f.write(answer)
f.close()

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

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
    print(pdict['x'])

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

And here is the module "persistent.py" which makes this possible

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

    Usage:
        from __future__ import with_statement
        from persistent import PersistentDict

        def main(pdict):
            # Your pogram's code goes here
            pass                          
                                          
        with PersistentDict("myfile.pkl") as pdict:
            main(pdict)                            
"""                                                
try:                                               
    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):
        try:
            file_in = open(self.path)
            self.pdict = pickle.load(file_in)
            file_in.close()
        except IOError:
            self.pdict = dict()
        return self.pdict
    def __exit__(self, *args):
        file_out = open(self.path, "w")
        pickle.dump(self.pdict, file_out)
        file_out.close()
        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 :)

 
0
 

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.

 
0
 

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

 
0
 

How would I make it into a class?

 
0
 
#first:
class NorbertQuest(object):
    #every function goes in here
    #every variable is renamed self.variable
    #so if i was "health" it would be "self.health"
   #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()
n.RunWhateverIsYourMainFunction()
 
0
 

I guess it would be the health function, but I'm not sure.

 
0
 

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)

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article