python开发——gzip压缩|解压缩
最近学习数据分析,需要使用python中的gzip模块,在百度上找到一篇很不错的文章,这里是可爱的传送门。
因为这是windows版本的,所以我在原作者的基础上,稍加修改,移植到Linux版本中,并附带python脚本程序。
gzip -- 支持gzip文件
这个模块提供了一些简单的接口来对文件进行压缩和解压缩,类似于GNU项目中得gzip
数据的压缩源于zlib模块的支持。
在gzip模块中提供了GzipFile类,在该类中提供了像open( ), compress( ), 和depress( )等一些方便的方法
GzipFile类在读写gzip格式的文件的时候,自动的压缩和解压缩数据类似于操作普通的文件对象。
在gzip模块中定义了一些方法:
gzip.open(filename, mode='rb', compresslevel = 9, encoding = None, errors = None, newline = None)
打开一个gzip已经压缩好的gzip格式的文件,并返回一个文件对象:file object 。
参数filename可以是正式的文件名,或者是已经存在的读写文件对象。
参数mode在操作二进制的时候使用:‘r', 'rb', 'a', 'ab', 'wb'
操作text的时候使用:'rt', 'at', 'wt'
默认是:'rb'
=========================================================================================
准备部分:
=========================================================================================
1.打开bash
2.创建data.txt,并复制到/tmp/demo中和/tmp中。
输入指令:vim data.txt
cp data.txt /tmp/democp data.txt /tmp
3.在/tmp中压缩文件
输入指令:
cd /tmp
gzip data.txt
ls data.txt
=========================================================================================
代码部分:
=========================================================================================
#!/usr/bin/env python
#_*_ coding=utf-8 _*_
import os
import gzip
def read_gz_file(path):
'''read the existing gzip-format file,and return the content of this file'''
if os.path.exists(path):
print '打开文件[{}]'.format(path)
with gzip.open(path,'rb') as pf:
return pf.read()
else:
print 'the path [{}] is not exist!'.format(path)
def write_gz_file(path,content):
'''write the byte-format content into the gzip-format file
so,with this way, we can creat the file if the path doesn't exist.
And we can write the content into the file if the file existing'''
print '写入文件:[{}] 内容:[{}]'.format(path, content)
with gzip.open(path,'w+') as fobj:
fobj.write(content)
def read_txt_write_gz(tpath,gzpath):
'''read the txt-format file with 'rb' and write this file content
to the gzip-format file'''
if os.path.exists(tpath):
if os.path.exists(gzpath):
print '打开文件:[{}]'.format(tpath)
with open(tpath, 'rb') as t:
print '打开文件:[{}]'.format(gzpath)
with gzip.open(gzpath, 'wb') as g:
print '写入内容:[{}]'.format(t)
g.writelines(t)
print '写入内容完成'
else:
print 'the path [{}]is not exist!'.format(gzpath)
else:
print 'the path [{}] is not exist!'.format(tpath)
def init():
#gz文件存放位置
global gz_file_path
gz_file_path = '/tmp/data.txt.gz'
#txt文件存放位置
global txt_file_path
txt_file_path = '/tmp/demo/data.txt'
def main():
init()
content = 'this is a byte message!\n'
write_gz_file(gz_file_path,content)
con = read_gz_file(gz_file_path)
print con
read_txt_write_gz(txt_file_path, gz_file_path)
con = read_gz_file(gz_file_path)
print con
if __name__ == '__main__':
main()