云萌主云应用官方论坛

标题: python使用pickle,json等序列化dict [打印本页]

作者: lady-niuniu    时间: 2016-12-30 00:55
标题: python使用pickle,json等序列化dict
来源:http://www.open-open.com/code/view/1420520368937


  1. import pickle, json, csv, os, shutil

  2. class PersistentDict(dict):
  3.     ''' Persistent dictionary with an API compatible with shelve and anydbm.

  4.     The dict is kept in memory, so the dictionary operations run as fast as
  5.     a regular dictionary.

  6.     Write to disk is delayed until close or sync (similar to gdbm's fast mode).

  7.     Input file format is automatically discovered.
  8.     Output file format is selectable between pickle, json, and csv.
  9.     All three serialization formats are backed by fast C implementations.

  10.     '''

  11.     def __init__(self, filename, flag='c', mode=None, format='pickle', *args, **kwds):
  12.         self.flag = flag                    # r=readonly, c=create, or n=new
  13.         self.mode = mode                    # None or an octal triple like 0644
  14.         self.format = format                # 'csv', 'json', or 'pickle'
  15.         self.filename = filename
  16.         if flag != 'n' and os.access(filename, os.R_OK):
  17.             fileobj = open(filename, 'rb' if format=='pickle' else 'r')
  18.             with fileobj:
  19.                 self.load(fileobj)
  20.         dict.__init__(self, *args, **kwds)

  21.     def sync(self):
  22.         'Write dict to disk'
  23.         if self.flag == 'r':
  24.             return
  25.         filename = self.filename
  26.         tempname = filename + '.tmp'
  27.         fileobj = open(tempname, 'wb' if self.format=='pickle' else 'w')
  28.         try:
  29.             self.dump(fileobj)
  30.         except Exception:
  31.             os.remove(tempname)
  32.             raise
  33.         finally:
  34.             fileobj.close()
  35.         shutil.move(tempname, self.filename)    # atomic commit
  36.         if self.mode is not None:
  37.             os.chmod(self.filename, self.mode)

  38.     def close(self):
  39.         self.sync()

  40.     def __enter__(self):
  41.         return self

  42.     def __exit__(self, *exc_info):
  43.         self.close()

  44.     def dump(self, fileobj):
  45.         if self.format == 'csv':
  46.             csv.writer(fileobj).writerows(self.items())
  47.         elif self.format == 'json':
  48.             json.dump(self, fileobj, separators=(',', ':'))
  49.         elif self.format == 'pickle':
  50.             pickle.dump(dict(self), fileobj, 2)
  51.         else:
  52.             raise NotImplementedError('Unknown format: ' + repr(self.format))

  53.     def load(self, fileobj):
  54.         # try formats from most restrictive to least restrictive
  55.         for loader in (pickle.load, json.load, csv.reader):
  56.             fileobj.seek(0)
  57.             try:
  58.                 return self.update(loader(fileobj))
  59.             except Exception:
  60.                 pass
  61.         raise ValueError('File not in a supported format')

  62. if __name__ == '__main__':
  63.     import random

  64.     # Make and use a persistent dictionary
  65.     with PersistentDict('/tmp/demo.json', 'c', format='json') as d:
  66.         print(d, 'start')
  67.         d['abc'] = '123'
  68.         d['rand'] = random.randrange(10000)
  69.         print(d, 'updated')

  70.     # Show what the file looks like on disk
  71.     with open('/tmp/demo.json', 'rb') as f:
  72.         print(f.read())
复制代码







欢迎光临 云萌主云应用官方论坛 (https://yunmengzhu.com/) Powered by Discuz! X3.4