Import pickle, JSON, CSV, OS, Shutilclass persistentdict (dict): ' Persistent dictionary with a API compatible with s Helve and ANYDBM. The dict is kept in memory, so the dictionary operations run as fast as a regular dictionary. Write to disk was delayed until close or sync (similar to GDBM's fast mode). Input file format is automatically discovered. Output file format is selectable between Pickle, JSON, and CSV. All three serialization formats is backed by fast C implementations. "Def __init__ (self, filename, flag= ' C ', mode=none, format= ' Pickle ', *args, **kwds): Self.flag = Flag # r=readonly, C=create, or n=new self.mode = mode # None or an octal triple like 0644 Self.format = format # ' CSV ', ' json ', or ' pickle ' self.filename = filename if flag! = ' N ' and os.access (filename, os. R_OK): fileobj = open (filename, ' RB ' if format== ' pickle ' Else ' r ') WITH Fileobj:self.load (fileobj) dict.__init__ (self, *args, **kwds) def sync (self): ' Write Dict to disk ' if Self.flag = = ' R ': return filename = self.filename tempname = filename + ' . tmp ' fileobj = open (Tempname, ' WB ' if self.format== ' pickle ' Else ' W ') Try:self.dump (fileobj) Except Exception:os.remove (tempname) raise Finally:fileobj.close () s Hutil.move (Tempname, Self.filename) # Atomic Commit if Self.mode is not None:os.chmod (Self.filename, Self.mode) def close (self): Self.sync () def-__enter__ (self): return-Self-def __exit__ (self, *exc_i NFO): Self.close () def dump (self, fileobj): if Self.format = = ' csv ': Csv.writer (fileobj). Write Rows (Self.items ()) elif Self.format = = ' json ': json.dump (Self, fileobj, separators= (', ', ': ')) el if Self.format = = ' PicklE ': Pickle.dump (Dict (self), fileobj, 2) else:raise notimplementederror (' Unknown format: ' + Repr (Self.format)) def load (self, fileobj): # Try formats from most restrictive to least restrictive for Loader in (Pickle.load, Json.load, Csv.reader): Fileobj.seek (0) Try:return SELF.UPDA TE (loader (fileobj)) except Exception:pass raise ValueError (' File not in a supported form At ') if __name__ = = ' __main__ ': Import random # Make and use a persistent dictionary with persistentdict ('/tmp/dem O.json ', ' C ', format= ' json ') as D:print (d, ' start ') d[' abc '] = ' 123 ' d[' rand '] = Random.randrange (10 Print (d, ' updated ') # Show What the file looks like on disk with open ('/tmp/demo.json ', ' RB ') as F: Print (F.read ())
Python uses serialization dict such as Pickle,json