Python中使用tarfile压缩、解压tar归档文件示例

yipeiwu_com5年前Python基础

Python自带的tarfile模块可以方便读取tar归档文件,牛b的是可以处理使用gzip和bz2压缩归档文件tar.gz和tar.bz2。
与tarfile对应的是zipfile模块,zipfile是处理zip压缩的。请注意:os.system(cmd)可以使Python脚本执行命令,当然包括:tar -czf  *.tar.gz *,tar -xzf *.tar.gz,unzip等,当我觉得这样尽管可以解决问题,但我觉得很业余。

使用tarfile压缩

复制代码 代码如下:

import tarfile
 
#创建压缩包名
tar = tarfile.open("/tmp/tartest.tar.gz","w:gz")
#创建压缩包
for root,dir,files in os.walk("/tmp/tartest"):
    for file in files:
        fullpath = os.path.join(root,file)
        tar.add(fullpath)
tar.close()

使用tarfile解压
复制代码 代码如下:

def extract(tar_path, target_path):
    try:
        tar = tarfile.open(tar_path, "r:gz")
        file_names = tar.getnames()
        for file_name in file_names:
            tar.extract(file_name, target_path)
        tar.close()
    except Exception, e:
        raise Exception, e

其中open的原型是:

复制代码 代码如下:

tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)

mode的值有:
复制代码 代码如下:

'r' or 'r:*'   Open for reading with transparent compression (recommended).
'r:'   Open for reading exclusively without compression.
'r:gz'   Open for reading with gzip compression.
'r:bz2'   Open for reading with bzip2 compression.
'a' or 'a:'   Open for appending with no compression. The file is created if it does not exist.
'w' or 'w:'   Open for uncompressed writing.
'w:gz'   Open for gzip compressed writing.
'w:bz2'   Open for bzip2 compressed writing.

更多请参考:tarfile — Read and write tar archive files

相关文章

python中 * 的用法详解

1、表示乘号 2、表示倍数,例如: def T(msg,time=1): print((msg+' ')*time) T('hi',3) 打印结果(打印3次): hi h...

python可视化篇之流式数据监控的实现

python可视化篇之流式数据监控的实现

preface 流式数据的监控,以下主要是从算法的呈现出发,提供一种python的实现思路 其中: 1.python是2.X版本 2.提供两种实现思路,一是基于matplotli...

Python注释详解

注释用于说明代码实现的功能、采用的算法、代码的编写者以及创建和修改的时间等信息。 注释是代码的一部分,注释起到了对代码补充说明的作用。 Python注释 Python单行注释以#开头,单...

pytorch 图像预处理之减去均值,除以方差的实例

pytorch 图像预处理之减去均值,除以方差的实例

如下所示: #coding=gbk ''' GPU上面的环境变化太复杂,这里我直接给出在笔记本CPU上面的运行时间结果 由于方式3需要将tensor转换到GPU上面,这一过程很消...

python基于urllib实现按照百度音乐分类下载mp3的方法

本文实例讲述了python基于urllib实现按照百度音乐分类下载mp3的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python #-*- cod...