返回顶部

python使用pickle,json等序列化dict

[复制链接]
lady-niuniuLv.2 显示全部楼层 发表于 2016-12-30 00:55:47 |阅读模式 打印 上一主题 下一主题

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
来源: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())
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

云萌主 云萌主-BIGSAAS旗下,由北京合智互联信息技术有限公司在2018年创立,为广大云应用技术爱好者的平台。在云萌主论坛可以查看云应用技术文章、云产品产品最新资讯、技术问答、技术视频。在畅游云上技术的同时,学到最新的云应用产品和技术。
  • 微信公众号

  • Powered by Discuz! X3.4 | Licensed | Copyright © 2001-2022, Aliyun Cloud. | 星点互联设计
  • 京ICP备18052714号 | 营业执照 | |合智互联| QQ