[Python] python zip和unzip数据 →→→→→进入此内容的聊天室

来自 , 2020-06-05, 写在 Python, 查看 108 次.
URL http://www.code666.cn/view/48e95c45
  1. # zipping and unzipping a string using the zlib module
  2. # a very large string could be zipped and saved to a file speeding up file writing time
  3. # and later reloaded and unzipped by another program speeding up reading of the file
  4. # tested with Python24      vegaseat      15aug2005
  5.  
  6. import zlib
  7.  
  8. str1 = \
  9. """Dallas Cowboys football practice at Valley Ranch was delayed on Wednesday
  10. for nearly two hours.  One of the players, while on his way to the locker
  11. room happened to look down and notice a suspicious looking, unknown white
  12. powdery substance on the practice field.
  13.  
  14. The coaching staff immediately suspended practice while the FBI was
  15. called in to investigate.  After a complete field analysis, the FBI
  16. determined that the white substance unknown to the players was the goal
  17. line.
  18.  
  19. Practice was resumed when FBI Special Agents decided that the team would not
  20. be likely to encounter the substance again.
  21. """
  22.  
  23. print '-'*70  # 70 dashes for the fun of it
  24. print str1
  25. print '-'*70
  26.  
  27. crc_check1 = zlib.crc32(str1)
  28. print "crc before zip=", crc_check1
  29.  
  30. print "Length of original str1 =", len(str1)
  31. # zip compress the string
  32. zstr1 = zlib.compress(str1)
  33.  
  34. print "Length of zipped str1 =", len(zstr1)
  35.  
  36. filename = 'Dallas.zap'
  37.  
  38. # write the zipped string to a file
  39. fout = open(filename, 'w')
  40. try:
  41.     print >> fout, zstr1
  42. except IOError:
  43.     print "Failed to open file..."
  44. else:
  45.     print "done writing", filename
  46. fout.close()
  47.  
  48. # read the zip file back
  49. fin = open(filename, 'r')
  50. try:
  51.     zstr2 = fin.read()
  52. except IOError:
  53.     print "Failed to open file..."
  54. else:
  55.     print "done reading", filename
  56. fin.close()
  57.  
  58. # unzip the zipped string from the file
  59. str2 = zlib.decompress(zstr2)
  60.  
  61. print '-'*70
  62. print str2
  63. print '-'*70
  64.  
  65. crc_check2 = zlib.crc32(str2)
  66. print "crc after unzip =", crc_check2, "(check sums should match)"
  67. #//python/5752

回复 "python zip和unzip数据"

这儿你可以回复上面这条便签

captcha