import pickle, json, csv, os, shutil

class PersistentDict(dict):
''' Persistent dictionary with an API compatible with shelve and anydbm. The dict is kept in memory, so the dictionary operations run as fast as
a regular dictionary. Write to disk is 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 are 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()
shutil.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_info):
self.close() def dump(self, fileobj):
if self.format == 'csv':
csv.writer(fileobj).writerows(self.items())
elif self.format == 'json':
json.dump(self, fileobj, separators=(',', ':'))
elif 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.update(loader(fileobj))
except Exception:
pass
raise ValueError('File not in a supported format') if __name__ == '__main__':
import random # Make and use a persistent dictionary
with PersistentDict('/tmp/demo.json', 'c', format='json') as d:
print(d, 'start')
d['abc'] = '123'
d['rand'] = random.randrange(10000)
print(d, 'updated') # Show what the file looks like on disk
with open('/tmp/demo.json', 'rb') as f:
print(f.read())

python使用pickle,json等序列化dict的更多相关文章

  1. python模块--pickle&json&shelve

    使用file文件处理时,写入的必须是str ,否则会报错. 例如:要把一个字典写入文件,写入时会报错 ,就算转换成str格式写入,读取的时候也不能按照dict格式读. >>> inf ...

  2. 【python】python中的json、字典dict

    定义 python中,json和dict非常类似,都是key-value的形式,而且json.dict也可以非常方便的通过dumps.loads互转.既然都是key-value格式,为啥还需要进行格式 ...

  3. Python第十四天 序列化 pickle模块 cPickle模块 JSON模块 API的两种格式

    Python第十四天 序列化  pickle模块  cPickle模块  JSON模块  API的两种格式 目录 Pycharm使用技巧(转载) Python第一天  安装  shell  文件 Py ...

  4. Python模块:shutil、序列化(json&pickle&shelve)、xml

    shutil模块: 高级的 文件.文件夹.压缩包 处理模块 shutil.copyfileobj(fscr,fdst [, length])   # 将文件内容拷贝到另一个文件中 import shu ...

  5. python学习之文件读写,序列化(json,pickle,shelve)

    python基础 文件读写 凡是读写文件,所有格式类型都是字符串形式传输 只读模式(默认) r  f=open('a.txt','r')#文件不存在会报错 print(f.read())#获取到文件所 ...

  6. Python:序列化 pickle JSON

    序列化 在程序运行的过程中,所有的变量都储存在内存中,例如定义一个dict d=dict(name='Bob',age=20,score=88) 可以随时修改变量,比如把name修改为'Bill',但 ...

  7. python开发模块基础:序列化模块json,pickle,shelve

    一,为什么要序列化 # 将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化'''比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?现在我们能想到的方法就是存在文 ...

  8. python入门之json与pickle数据序列化

    前提实例: 将一个字典存放在文件里 #存入数据info = { 'name':'chy', 'age':18 } f = open("test.txt","w" ...

  9. Python全栈--7模块--random os sys time datetime hashlib pickle json requests xml

    模块分为三种: 自定义模块 内置模块 开源模块 一.安装第三方模块 # python 安装第三方模块 # 加入环境变量 : 右键计算机---属性---高级设置---环境变量---path--分号+py ...

随机推荐

  1. 【反演复习计划】【bzoj3994】约数个数和

    首先要用数学归纳证明一个结论,不过因为我实在是懒得打公式了... 先发代码吧. #include<bits/stdc++.h> #define N 50005 using namespac ...

  2. Nightmare安装and一个小例子

    前端的功能测试 官方说法A high-level browser automation library,翻译过来就是高级浏览器自动化库 常用于UI测试和爬网 功能测试必须在真正浏览器做,现在有四种方法 ...

  3. 手机端图片插件可缩放 旋转 全屏查看photoswipe

    官方介绍PhotoSwipe 是专为移动触摸设备设计的相册/画廊.兼容所有iPhone.iPad.黑莓6+,以及桌面浏览器.底层实现基于HTML/CSS/JavaScript,是一款免费开源的相册产品 ...

  4. 使用@CrossOrigin实现跨域请求

    1.毕设使用的是react+java开发的网上书城,大家都知道react主要是视图(表现层或页面),数据的处理还是通过java来实现的,所以我的毕设相当于是两个项目组成的,一个是前端项目,一个是后台项 ...

  5. sql 获取字符串首字母,循环

    //字符串首字母 CREATE FUNCTION GetInitialLetter(@ChineseString NVARCHAR()) RETURNS NVARCHAR() AS BEGIN DEC ...

  6. 简单unix 局域网的TCP会话

    client.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <e ...

  7. tcpdump学习(2):基本使用

    安装好tcpdump之后,运行tcpdump: 1. tcpdump -D 获取网络适配器列表,以下是在Ubuntu上获取到的结果: root@holmesian-laptop:~# tcpdump ...

  8. windows下tortoiseGit安装和使用

    一.安装git for windows 首先下载git for windows客户端http://msysgit.github.io/ 安装过程没什么特别的,不停next就ok了     图太多就不继 ...

  9. 平滑部署war包到tomcat-deploy.sh

    #!/bin/sh #check war exists echo "check war exists" war_file_path=/data/tomcat8/webapps wa ...

  10. typescript 定义全局变量以及扩展原生js对象

    使用“declare global”操作即可. 项目根目录下新建myDeclareFile.d.ts declare global { interface Navigator { mediaSessi ...