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 ...
随机推荐
- CSDN博客排名记录
截止今天,在CSDN的博客排名终于从"千里之外"变成具体的排名数字了.根据CSDN的规则,只有排名在20000以内才能显示具体的排名.从2015年5月11日开始写了第一篇博客.后来 ...
- hdu 1507(二分图匹配)
Uncle Tom's Inherited Land* Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (J ...
- PHP7中php.ini、php-fpm和www.conf的配置(转)
根据前文 <2015博客升级记(五):CentOS 7.1编译安装PHP7> 的 configure 编译参数设定,安装后的PHP7配置文件所在路径是 /usr/local/php7/et ...
- GridView的TemplateField
BoundField只能显示一个单独的数据字段.如果我们想要在一个GridView列中显示两个或者更多的数据字段的值的时候该怎么办呢? 1. GridView的一列同时显示数据源中的两个字段 现需要显 ...
- HDU 1233.还是畅通工程-最小生成树(Prime)
还是畅通工程 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Subm ...
- boost::operators
boost 的 operators 提供了comparison operators.arithmetic operators.operators for iterators 操作.虽然使用 C++ 的 ...
- autossh反向隧道
实验目标 有两台主机: hostA: 阿里云公网主机 hostB: 本地内网主机 需求实现: 在hostB上使用autossh将hostB的80的端口映射到hostA的8080,使得其他机器访问hos ...
- UVA GCD - Extreme (II)
discription Given the value of N, you will have to find the value of G. The definition of G is given ...
- 【KM算法】HDU2255-奔小康赚大钱
KM算法的裸体.O(n^4)的模板,实际上在增广路径的时候依然有冗余,可以用bfs优化到O(n^3). #include <iostream> #include <cstdio> ...
- python3开发进阶-Django视图(View)的常见用法
阅读目录 简述Django的View(视图) CBV和FBV Request对象和Response对象 Django组件(render,redirect)详解 一.简述Django的View(视图) ...