Python中使用tarfile压缩、解压tar归档文件示例
来源:互联网 发布:算法导论 pdf 百度云 编辑:程序博客网 时间:2024/05/24 06:29
Python自带的tarfile模块可以方便读取tar归档文件,牛b的是可以处理使用gzip和bz2压缩归档文件tar.gz和tar.bz2。
使用tarfile解压
mode的值有:
与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.
0 0
- Python中使用tarfile压缩、解压tar归档文件示例
- Python中使用tarfile压缩、解压tar归档文件
- Python下使用tarfile模块来实现文件归档压缩与解压
- Python下使用tarfile模块来实现文件归档压缩与解压
- 使用python tarfile 模块在 Windows 平台正确解压 tar 文件
- python中的压缩、解压包tarfile
- 在Linux中使用zip、tar压缩、解压文件
- python学习笔记 --- tar文件压缩解压
- python_使用tarfile压缩及解压的方法
- python脚本编程:使用zip或者tar压缩和解压文件
- U3D中C#压缩解压文件示例
- linux tar压缩解压文件
- python 8-3-1 使用tarfile可以实现文件的压缩打包
- python 8-3-1 使用tarfile可以实现文件的压缩打包
- tar解压 归档中找不到错误
- tar:从压缩包中解压出指定文件
- python的tarfile模块实例 python把文件夹压缩成tar格式文件的例子
- python的tarfile模块实例 python把文件夹压缩成tar格式文件的例子
- Mac Ant安装
- AngularJSb表单校验示例
- 关于第三方环信的使用
- 【ACM】1020:迭代法
- js阻止事件冒泡
- Python中使用tarfile压缩、解压tar归档文件示例
- ZOJ 1078
- Android开发-API指南-<application>[原创译文]
- String,StringBuffer,StringBuilder的区别
- 【ACM】1043:字符串排序
- 更改Eclipse下Tomcat的部署目录
- CSS动画animate.css动画效果全集中文解释
- unity图片打包
- LeetCode:Power of Two