Python实现压缩与解压gzip大文件的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python实现压缩与解压gzip大文件的方法。分享给大家供大家参考,具体如下:

#encoding=utf-8
#author: walker
#date: 2015-10-26
#summary: 测试gzip压缩/解压文件
import gzip
BufSize = 1024*8
def gZipFile(src, dst):
  fin = open(src, 'rb')
  fout = gzip.open(dst, 'wb')
  in2out(fin, fout)
def gunZipFile(gzFile, dst):
  fin = gzip.open(gzFile, 'rb')
  fout = open(dst, 'wb')
  in2out(fin, fout)
def in2out(fin, fout):
  while True:
    buf = fin.read(BufSize)
    if len(buf) < 1:
      break
    fout.write(buf)
  fin.close()
  fout.close()
if __name__ == '__main__':
  src = r'D:\tmp\src.txt'
  dst = r'D:\tmp\src.txt.gz'
  ori = r'D:\tmp\ori.txt'
  gZipFile(src, dst)
  print('gZipFile over!')
  gunZipFile(dst, ori)
  print('gunZipFile over!')

也可以简单地封装成一个类:

class GZipTool:
  def __init__(self, bufSize):
    self.bufSize = bufSize
    self.fin = None
    self.fout = None
  def compress(self, src, dst):
    self.fin = open(src, 'rb')
    self.fout = gzip.open(dst, 'wb')
    self.__in2out()
  def decompress(self, gzFile, dst):
    self.fin = gzip.open(gzFile, 'rb')
    self.fout = open(dst, 'wb')
    self.__in2out()
  def __in2out(self,):
    while True:
      buf = self.fin.read(self.bufSize)
      if len(buf) < 1:
        break
      self.fout.write(buf)
    self.fin.close()
    self.fout.close()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python URL操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

详解Python中的Cookie模块使用

详解Python中的Cookie模块使用

最近在用GAE开发自己的博客程序。虽然GAE的API没有显式的提供操作Cookie的方法,但他现有的架构,使我们有足够的自由来操作Cookie。 Cookie 模块,顾名思义,就是用来操...

Python tkinter实现图片标注功能(完整代码)

.tkinter tkinter是Python下面向tk的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter的优点是简单易用、与Python的结合度好。tkinte...

python 两个数据库postgresql对比

这篇文章主要介绍了python 两个数据库postgresql对比,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 比较两个postgr...

python smtplib模块自动收发邮件功能(二)

python smtplib模块自动收发邮件功能(二)

接上篇python smtplib模块自动收发邮件功能(一) ,用python smtplib模块实现了发送邮件程序了,那么接下来我们需要现在要解决的问题如何在 test_report\...

Swift 3.0在集合类数据结构上的一些新变化总结

一、Array数组的更改 array数组中修改的API示例如下: //创建大量相同元素的数组 //创建有10个String类型元素的数组,并且每个元素都为字符串"Hello" //s...