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 ...
随机推荐
- 【bzoj4272】筐子放球
看题解会的系列…… 详细解释先坑着,以后补…… #include<bits/stdc++.h> #define N 200005 using namespace std; ,tot=,cn ...
- jsp页面点击打印按钮调用系统 的打印功能
<script language=javascript> function prt() { var btn_obj = document.getElementById("prin ...
- jquery.qrcode生成二维码支持中文
基本使用方法: 1.首先在页面中加入jquery库文件和qrcode插件. <script type="text/javascript" src="jquery.j ...
- Selenium2+python自动化35-获取元素属性【转载】
前言 通常在做断言之前,都要先获取界面上元素的属性,然后与期望结果对比.本篇介绍几种常见的获取元素属性方法. 一.获取页面title 1.有很多小伙伴都不知道title长在哪里,看下图左上角. 2.获 ...
- python基础之初识python
Python的发展史 1989年圣诞节期间,吉多·范罗苏姆为了打发时间,开发了python这门语言.真他妈牛逼. Python崇尚优美.清晰.简单,是一门优秀并广泛使用的语言.2007年在TIOBE榜 ...
- eclipse 关键字高亮显示
关键字高亮显示(变量.函数名……) Toggle Mark Occurrences (Alt + Shift + O), 也可以在eclipse主界面的快捷工具栏:按下那个小黄蜡笔图标,来设置高亮显 ...
- Codeforces 855E - Salazar Slytherin's Locket
855E - Salazar Slytherin's Locket 题意 给出一个区间,问这个区间内有多少个数满足,将这个数转化为某个进制后,所有数的数量都为偶数. 分析 谁能想到 数位DP 的裸题竟 ...
- Codeforces Round #352 (Div. 1) B. Robin Hood (二分)
B. Robin Hood time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- [UOJ300]吉夫特
直接上lucas定理,可以得到$\binom nm=1$等价于$m$是$n$的子集(二进制) 因为数字两两不同,所以设$f_i$表示以$i$开头的满足要求的序列有多少个,转移就是$f_i\gets f ...
- 【AC自动机】【动态规划】poj3691 DNA repair
http://blog.csdn.net/kk303/article/details/6929641 http://blog.csdn.net/human_ck/article/details/657 ...