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

Recommended Answers

All 9 Replies

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

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

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

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

How would I make it into a class?

#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()

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

Member Avatar for leegeorg07

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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.