使用zipfile
归档data
词典:
import os, sys, cPickle, zipfile
data = {1: 'one'}
pfile = r'c:\temp\myPickle.p'
cPickle.dump( data, open( pfile, "wb" ))
zfilename = r'c:\temp\myArchive.zip'
zfile = zipfile.ZipFile(zfilename, "w", zipfile.ZIP_DEFLATED)
zfile.write(pfile, os.path.basename(pfile))
zfile.close()
该方法在本地驱动器上生成两个文件:一个是pickle,另一个是zip。
要获取pickle data
zip文件需要取消存档:
fh = open(zfilename, 'rb')
z = zipfile.ZipFile(fh)
for each in z.namelist():
z.extract(each, r'c:\temp')
fh.close()
如何简化流程?
答案 0 :(得分:1)
请改用gzip
。它在您编写文件时压缩文件,因此不需要中间文件。
import cPickle as pickle
import gzip
data = {1: 'one'}
pfile = r'test.pkl.gz'
pickle.dump(data, gzip.open(pfile, "w"), pickle.HIGHEST_PROTOCOL)
print pickle.load(gzip.open(pfile))