Python uses serialization dict such as Pickle,json

Source: Internet
Author: User
Tags serialization

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.