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())

最新文章

  1. Entity Framework基础01
  2. JavaScript 字符 "转换
  3. 【Visual Lisp】表处理专题
  4. Magento中,调用静态块的几种方法
  5. c++ const 关键字 学习笔记
  6. C、Shell、Perl基于Tomcat开发CGI程序环境配置
  7. 在C语言中使用scanf语句时遇到的问题总结
  8. 设置MySQL数据表主键
  9. Session or Cookie?是否有必要使用Tomcat等一下Web集装箱Session
  10. MyBatis:打印SQL 日志
  11. ASP.NET Core的身份认证框架IdentityServer4(5)- 包和构建
  12. 关于Serializable的serialVersionUID
  13. Eclipse设置新建jsp文件默认模板
  14. 《Linux就该这么学》
  15. PHP开发:Eclipse版环境配置
  16. inf
  17. 轻量级ORM工具Simple.Data
  18. hdu-1800(字符串hash)
  19. Sqoop增量导入
  20. Python 字符串操作,截取,长度

热门文章

  1. 用java实现word转html
  2. PEP 3106 -- Revamping(改进) dict.keys(), .values() and .items()
  3. (十一)数组array
  4. easyUI之datagrid
  5. Codeforces 1023 C.Bracket Subsequence-STL(vector) (Codeforces Round #504 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Fi)
  6. JavaScript处理异步请求的几种方式(取异步函数返回值)
  7. 软Raid5,LVM,3T大硬盘纠缠操作的问题
  8. [AGC012D]Colorful Balls
  9. FCL研究-目录
  10. hadoop InputSplit