每日一模块-gzip

一、gzip概述

gzip是用来解压Linux中的以命令gzip生成的以gz为后缀的压缩文件,常见如:file.tar.gz

压缩命令:tar -czvf  xxx.tar.gz  xxx.txt  -C 要压缩的文件路径

解压命令:tar -zxvf  xxx.tar.gz -C 指定解压后文件存放的路径

二、gzip的创建、压缩、解压使用

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# DevVersion: Python3.6
# Date: 2019-11-30 22:01
# Author: SunXiuWen
import os
import gzip


# 创建gzip文件:
def gen_new_gzip_file(path, content):
    """
    以字节写入更快,注意写入字符串要编码程Unicode
    :param path: 压缩后文件路径
    :return:
    """
    with gzip.open(path, 'wb') as f:
        f.write(content.encode('utf-8'))


# file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test.gz')
# content = "Lost of content here 这里有很多内容--->"
# gen_new_gzip_file(file_path, content)

# 压缩现有文件
def gen_exist_file_to_gzip_file(file1, file2):
    """
    通过gzip模块压缩现有的文件
    :param file1: 现有文件路径
    :param file2: 解压后文件存放路径及文件名
    :return:
    """
    with open(file1, 'rb') as f_in, gzip.open(file2, 'wb') as f_out:
        f_out.writelines(f_in)


# file_path_1 = '01.pdf'
# file_path_2 = os.path.join(os.path.dirname(os.path.abspath(__file__)), '01.pdf.gz')
# gen_exist_file_to_gzip_file(file_path_1, file_path_2)


# 解压gz文件
def uz_gz(path):
    """
    :param path: gz文件的路径
    :return: 
    """
    f_name = path.rstrip('.gz')
    g_file = gzip.GzipFile(path)
    open(f_name, 'wb+').write(g_file.read())
    g_file.close()


file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '01.pdf.gz')
uz_gz(file_path)

猜你喜欢

转载自www.cnblogs.com/sunxiuwen/p/11964424.html