python实现在pickling的时候压缩的方法

WBOY
Release: 2016-06-16 08:41:39
Original
1147 people have browsed it

本文实例讲述了python实现在pickling的时候压缩的方法。分享给大家供大家参考。

具体方法如下:

import cPickle,gzip
def save(filename,*objects):
  fil1 = gzip.open(filename,'wb')
  for obj in objects:
    cPickle.dump(obj,fil1,protocol = 2)
    fil1.close()
def load(filename):
  fil1 = gzip.open(filename,'rb')
  while True:
    try:
      yield cPickle.load(fil1)
    except EOFError:
      break
  fil1.close()
  
  
data1 = ['abc',12,23]  #几个测试数据
data2 = {1:'aaa',"b":'dad'}
data3 = (1,2,4)
data = list([data1,data2,data3])
save('data.zip',data)

iter = load('data.zip')
for item in iter:
  for data in item:
    print data

Copy after login

本文实例测试环境为Python2.7.6

程序运行结果如下:

['abc', 12, 23]
{1: 'aaa', 'b': 'dad'}
(1, 2, 4)

Copy after login

在程序运行的同时会在同级目录下生成data.zip文件。

希望本文所述对大家Python程序设计的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template