python中zip和unzip数据的方法

yipeiwu_com5年前Python基础

本文实例讲述了python zip和unzip数据的方法。分享给大家供大家参考。具体实现方法如下:

# zipping and unzipping a string using the zlib module
# a very large string could be zipped and saved to a file speeding up file writing time 
# and later reloaded and unzipped by another program speeding up reading of the file
# tested with Python24   vegaseat   15aug2005
import zlib
str1 = \
"""Dallas Cowboys football practice at Valley Ranch was delayed on Wednesday 
for nearly two hours. One of the players, while on his way to the locker
room happened to look down and notice a suspicious looking, unknown white
powdery substance on the practice field.
The coaching staff immediately suspended practice while the FBI was
called in to investigate. After a complete field analysis, the FBI
determined that the white substance unknown to the players was the goal
line.
Practice was resumed when FBI Special Agents decided that the team would not
be likely to encounter the substance again.
"""
print '-'*70 # 70 dashes for the fun of it
print str1
print '-'*70
crc_check1 = zlib.crc32(str1)
print "crc before zip=", crc_check1
print "Length of original str1 =", len(str1)
# zip compress the string
zstr1 = zlib.compress(str1)
print "Length of zipped str1 =", len(zstr1)
filename = 'Dallas.zap'
# write the zipped string to a file
fout = open(filename, 'w')
try:
  print >> fout, zstr1
except IOError:
  print "Failed to open file..."
else:
  print "done writing", filename
fout.close()
# read the zip file back
fin = open(filename, 'r')
try:
  zstr2 = fin.read()
except IOError:
  print "Failed to open file..."
else:
  print "done reading", filename
fin.close()
# unzip the zipped string from the file
str2 = zlib.decompress(zstr2)
print '-'*70
print str2
print '-'*70
crc_check2 = zlib.crc32(str2)
print "crc after unzip =", crc_check2, "(check sums should match)"

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

相关文章

Python实现数据结构线性链表(单链表)算法示例

Python实现数据结构线性链表(单链表)算法示例

本文实例讲述了Python实现数据结构线性链表(单链表)算法。分享给大家供大家参考,具体如下: 初学python,拿数据结构中的线性链表存储结构练练手,理论比较简单,直接上代码。 #...

详解用pyecharts Geo实现动态数据热力图城市找不到问题解决

详解用pyecharts Geo实现动态数据热力图城市找不到问题解决

pyecharts 是一个用于生成 Echarts 图表的类库。 Echarts 是百度开源的一个数据可视化 JS 库。主要用于数据可视化。 本文主要是用pycharts中的Geo绘制中...

Python编程深度学习绘图库之matplotlib

Python编程深度学习绘图库之matplotlib

matplotlib是python的一个开源的2D绘图库,它的原作者是John D. Hunter,因为在设计上借鉴了matlab,所以成为matplotlib。和Pillow一样是被广...

Python实现制度转换(货币,温度,长度)

人民币和美元是世界上通用的两种货币之一,写一个程序进行货币间币值转换,其中: 人民币和美元间汇率固定为:1美元 = 6.78人民币。 程序可以接受人民币或美元输入,转换为美元或人民币输出...

Python提取支付宝和微信支付二维码的示例代码

Python提取支付宝和微信支付二维码的示例代码

支付宝或者微信支付导出的收款二维码,除了二维码部分,还有很大一块背景图案,例如下面就是微信支付的收款二维码: 有时候我们仅仅只想要图片中间的方形二维码部分,为了提取出中间部分,我们可以...