On Thu, Feb 14, 2013 at 4:05 PM, Dave Angel <da...@davea.name> wrote:
> On 02/14/2013 04:33 PM, Prasad, Ramit wrote: > >> Dave Angel wrote: >> >>> On 02/14/2013 12:35 PM, Prasad, Ramit wrote: >>> >>>> neubyr wrote: >>>> >>>>> I am not sure how to save an object in memory to a file before exiting >>>>> the program. Any examples or >>>>> related documentation links would be really helpful. I am guessing it >>>>> would be using some kind of >>>>> before teardown method, but not sure about it. Any help? >>>>> >>>> >>>> Look at the pickle or shelve modules. >>>> http://www.doughellmann.com/**PyMOTW/pickle/index.html<http://www.doughellmann.com/PyMOTW/pickle/index.html> >>>> http://www.doughellmann.com/**PyMOTW/shelve/index.html<http://www.doughellmann.com/PyMOTW/shelve/index.html> >>>> >>>> >>> You miss the point. The OP wants to make sure the text file is saved no >>> matter how the program happens to exit. He's not asking how to format >>> the file. >>> >>> >> Hmm. Good point Dave, I did miss that point. >> >> My knee jerk response is a try/finally block, but I am sure there >> are better ways. >> >> # UNTESTED >> stored_data = {} >> try: >> stored_data = load_data() >> while True: >> #<do program> >> except Exception: >> raise # reraise exception to keep trace and still >> # propogate error for attention >> finally: >> store_data(stored_data) # Save data since we are exiting >> # (intentionally or not). >> > > That would be my reaction as well. I would, however make it conditional > on some changes having been made. That way if this program run only made > queries, the effort and risk of saving can be avoided. > > The other thing I'd recommend is to store the data in an alternate file, > and only delete the original when the alternate is ready to rename. That > way, you can't readily get into trouble if something crashes while saving. > > > > > Thanks Ramit and Dave! I haven't had chance to code/learn further, but I will give play with this soon. I do have a doubt regarding this - e.g. how would I implement this if my program/application is web based. For example, loading the text file during web server start and stop. Hope to try it out soon! - N
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor