shelve crashing under Win ME

gluckj at gmail.com gluckj at gmail.com
Sun Jul 1 02:36:55 EDT 2007


OK, here's my workaround for shelve -- it's primitive and obviously
much slower (it saves the entire dictionary each time), and you have
to manually save -- BUT: it works...even on the Win ME machine. And
it's possibly more universally portable in the long run than
shelve...Also, once you open the dictionary, it is just as fast
(perhaps faster?) than shelve for reading the contents (just not for
saving...)
--Joel

================

#! /usr/local/bin/python
"""
myshelve.py -- a simpler (safer though slower) approach to shelve
"""

#Import Modules
import os, cPickle

def msopen(path):
	""" open file containing pickled dict & return dict; if no such file,
create it & return empty dict """
	if os.access(path, os.R_OK):
		f=open(path, "r")
		mydict=cPickle.load(f)
		f.close()
		return(mydict)
	else:
		f=open(path, "w")
		cPickle.dump({}, f)
		f.close()
		return({})

def mssave(mydict,path):
	""" pickle and save the dict to the file, overwriting previous
contents """
	f=open(path, "w")
	cPickle.dump(mydict, f)
	f.close()

def mstest():
	f1="_myshelvetest_.txt"
	print "Testing myshelve..."
	print "1) New file:",f1
	if os.access(f1, os.F_OK): os.remove(f1)
	d1=msopen(f1)
	print "Contents of new file:",d1
	d2=msopen(f1)
	print "Contents on re-read:",d2
	print "2) Write/Read/Overwrite/Read..."
	d1={1:"hello",2:"there",3:"folks"}
	print "Test dict:",d1
	mssave(d1,f1)
	d2=msopen(f1)
	print "Loaded:",d2
	print "Equal?",d1==d2
	d1={1:"goodbye",2:"now",3:"folks"}
	print "Test dict:",d1
	mssave(d1,f1)
	d2=msopen(f1)
	print "Loaded:",d2
	print "Equal?",d1==d2
	print "** DONE **"
	os.remove(f1)

if __name__=="__main__": mstest()






More information about the Python-list mailing list