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

相关文章

解决Ubuntu pip 安装 mysql-python包出错的问题

问题描述如下,报没有找到mysql_config环境变量 $ pip install mysql-python Collecting MySQL-python==1.2.5 (f...

python中urlparse模块介绍与使用示例

简介 urlparse模块主要是用于解析url中的参数  对url按照一定格式进行 拆分或拼接。urlparse库用于把url解析为各个组件,支持file,ftp,http,h...

python的依赖管理的实现

主流开发语言的包管理工具一般都是支持依赖管理的,比如PHP的composer、Java的mvn。 对于python来说又该如何管理依赖呢? pip基本用法 python还不错,它提供了...

2019 Python最新面试题及答案16道题

1.Python是如何进行内存管理的? 答:从三个方面来说,一对象的引用计数机制,二垃圾回收机制,三内存池机制 一、对象的引用计数机制 Python内部使用引用计数,来保持追踪内存中的对...

python os.path模块常用方法实例详解

os.path模块主要用于文件的属性获取,在编程中经常用到,以下是该模块的几种常用方法。更多的方法可以去查看官方文档:http://docs.python.org/library/os....