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

yipeiwu_com7年前Python基础

本文实例讲述了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

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

程序运行结果如下:

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

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

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

相关文章

Python模拟登录验证码(代码简单)

废话不多说了,直接给大家贴代码了。 import urllib import urllib2 import cookielib def getImg(picurl): ''' req...

Python定义二叉树及4种遍历方法实例详解

Python定义二叉树及4种遍历方法实例详解

本文实例讲述了Python定义二叉树及4种遍历方法。分享给大家供大家参考,具体如下: Python & BinaryTree 1. BinaryTree (二叉树) 二叉树是有限个元素的...

python实现换位加密算法的示例

如下所示: def translationCipher(msg,key): result = [""]*key for i in range(key):#把每一列元素按...

python改变日志(logging)存放位置的示例

实现了简单版本的logging.config,支持一般的通过config文件进行配置。感觉还有更好的方法,是直接利用logging.config.fileConfig(log_confi...

Python中调用其他程序的方式详解

Python中调用其他程序的方式详解

前言 在Python中,可以方便地使用os模块来运行其他脚本或者程序,这样就可以在脚本中直接使用其他脚本或程序提供的功能,而不必再次编写实现该功能的代码。为了更好地控制运行的进程, 可...