python使用pickle,json等序列化dict
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的更多相关文章
- python模块--pickle&json&shelve
使用file文件处理时,写入的必须是str ,否则会报错. 例如:要把一个字典写入文件,写入时会报错 ,就算转换成str格式写入,读取的时候也不能按照dict格式读. >>> inf ...
- 【python】python中的json、字典dict
定义 python中,json和dict非常类似,都是key-value的形式,而且json.dict也可以非常方便的通过dumps.loads互转.既然都是key-value格式,为啥还需要进行格式 ...
- Python第十四天 序列化 pickle模块 cPickle模块 JSON模块 API的两种格式
Python第十四天 序列化 pickle模块 cPickle模块 JSON模块 API的两种格式 目录 Pycharm使用技巧(转载) Python第一天 安装 shell 文件 Py ...
- Python模块:shutil、序列化(json&pickle&shelve)、xml
shutil模块: 高级的 文件.文件夹.压缩包 处理模块 shutil.copyfileobj(fscr,fdst [, length]) # 将文件内容拷贝到另一个文件中 import shu ...
- python学习之文件读写,序列化(json,pickle,shelve)
python基础 文件读写 凡是读写文件,所有格式类型都是字符串形式传输 只读模式(默认) r f=open('a.txt','r')#文件不存在会报错 print(f.read())#获取到文件所 ...
- Python:序列化 pickle JSON
序列化 在程序运行的过程中,所有的变量都储存在内存中,例如定义一个dict d=dict(name='Bob',age=20,score=88) 可以随时修改变量,比如把name修改为'Bill',但 ...
- python开发模块基础:序列化模块json,pickle,shelve
一,为什么要序列化 # 将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化'''比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?现在我们能想到的方法就是存在文 ...
- python入门之json与pickle数据序列化
前提实例: 将一个字典存放在文件里 #存入数据info = { 'name':'chy', 'age':18 } f = open("test.txt","w" ...
- Python全栈--7模块--random os sys time datetime hashlib pickle json requests xml
模块分为三种: 自定义模块 内置模块 开源模块 一.安装第三方模块 # python 安装第三方模块 # 加入环境变量 : 右键计算机---属性---高级设置---环境变量---path--分号+py ...
随机推荐
- string与double的互相转换
#include <iostream> #include <string> #include <sstream> string DoubleToString(dou ...
- [ 总结 ] nginx 编译参数中文详解
贴出来,方便查找和学习. nginx 编译参数: --prefix=PATH 指向安装目录--sbin-path=PATH 指向(执行)程序文件--conf-path=PATH 指向 ...
- 使用 gulp 压缩 CSS
请务必理解如下章节后阅读此章节: 安装 Node 和 gulp 使用 gulp 压缩 JS 压缩 css 代码可降低 css 文件大小,提高页面打开速度. 我们接着将规律转换为 gulp 代码 规律 ...
- (7)case语句
(1)case 语法 case "变量" in 模式1) 命令序列1 ;; 模式2) 命令序列2 ;; 模式3) 命令序列3 ;; *) 无匹配后命令序列 esac (2)多系统配 ...
- (转)zeromq 安装
http://youzifei.iteye.com/blog/1698237 zeromq 今天在安装zeromq的时候费了好大的力气才算装好 下面来回顾一下在linux安装zeromq的过程 首先 ...
- 将双击“root的主文件”弹出的窗口设置为文件浏览器
1.双击桌面"root的文件夹"图标, 在过去Centos版本之前,每次双击“root主文件夹”都会弹出文件管理窗口: 解决办法: 关闭所有窗口后,重新双击图标: ...
- Dart类
Dart中没有访问控制符,无论类还是方法默认都是public 1.构造函数 构造函数可以没有方法体,并且this可以直接在传参时直接对实例赋值 Bicycle(this.cadence, this.s ...
- poj2253 最短路变形
题目连接:http://poj.org/problem?id=2253 Description Freddy Frog is sitting on a stone in the middle of a ...
- HDFS API 学习:几个常用的API
1.Hadoop-1.2.1 API 文档:http://hadoop.apache.org/docs/r1.2.1/api/ 2.几个API: create(Path f) :Opens an FS ...
- P2819 图的m着色问题
题目背景 给定无向连通图G和m种不同的颜色.用这些颜色为图G的各顶点着色,每个顶点着一种颜色.如果有一种着色法使G中每条边的2个顶点着不同颜色,则称这个图是m可着色的.图的m着色问题是对于给定图G和m ...