首页 > 技术文章 > python解压和压缩而文件

tjp40922 2020-06-06 21:45 原文

 1.tarfile模块的使用

import tarfile, os


def tar_file(output_name, source_dir):
    """
    压缩文件,当直线打包而不需要压缩的时候只需要把mode传成"w"
    :param output_name:压缩后的文件名
    :param sorce_dir: 要进行压缩的目录
    :return: bool
    """
    try:
        with tarfile.open(output_name, mode="w:gz") as tar:
            tar.add(source_dir, arcname=os.path.basename(source_dir))
            # tar.add(source_dir, arcname='wocao/wocao')  # arcname是压缩的收把文件按照arcname的目录组织的
            return True
    except Exception as err:
        print(err)
        return False


# tar_file('test.tar.gz', 'test')

def unztar(filename, tar_dir):
    """
    :param filename:要解压的文件
    :param tar_dir: 解压后文件存放位置
    :return: bool
    """
    try:
        with tarfile.open(filename) as fp:
            fp.extractall(tar_dir)
            return True
    except Exception as err:
        print(err)
        return False


unztar('test.tar.gz', './')

 

2.gzip的使用

import gzip


def unzip_file(path):
    """
    解压缩文件
    :param path:
    :return:
    """
    filename = path.replace('.gz', '')
    with open(filename, 'wb') as writer:
        open_gzFile = gzip.GzipFile(path)
        writer.write(open_gzFile.read())


def unzip_file1(path):
    """
    解压缩文件
    :param path:
    :return:
    """
    filename = path.replace('.gz', '')
    with open(filename, 'wb') as writer:
        open_gzFile = gzip.open(path)
        writer.write(open_gzFile.read())


def gz_file():
    """
    压缩文件,会创建一个和压缩文件同名的文件,没有.gz,并把内容写入
    :return:
    """

    content = "Lots of content here"
    with gzip.open('file.txt.gz', 'wb') as writer:
        writer.write(content.encode('utf-8'))


def gz_file1(path):
    """
    压缩现有的文件
    :return:
    """

    with open ('file.txt', 'rb')  as reader:
        with  gzip.open('file.txt.gz', 'wb') as writer:
            writer.write(reader.read())



if __name__ == '__main__':
    # unzip_file('./sitemap.xml.gz')
    # gz_file()
    gz_file1('./file.txt')

 

推荐阅读