码迷,mamicode.com
首页 > 其他好文 > 详细

每日一模块-gzip

时间:2019-12-01 00:33:29      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:后缀   lines   生成   创建   close   nic   lock   __file__   每日   

一、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)

 

 

每日一模块-gzip

标签:后缀   lines   生成   创建   close   nic   lock   __file__   每日   

原文地址:https://www.cnblogs.com/sunxiuwen/p/11964424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!