python解压和压缩而文件

 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')
复制代码

 

posted @   阿布_alone  阅读(378)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
TOP
点击右上角即可分享
微信分享提示