tar 压缩_python将zip压缩包转为gz.tar的方法

起因

老大:阿毛你把项目调研结果压缩为gz.tar文件发我一下,老总要看一下。。。

阿毛:老大zip文件可以吗?

老大:你把zip文件转换一下就OK了,什么???你电脑上没有可以压缩gz.tar格式的压缩软件???

0cb9d216ec8cb8040174ff598b2d1b3e.png

阿毛:反思中。。。工作中这个又时常需要将zip文件转换为gz.tar格式,所以常常将压缩为zip格式的文件来重新压缩成gz.tar格式发给他。

装一下压缩软件吧???还不想把电脑弄的乱七八糟的应用。能偷懒就不想动手,灵机一动,那就用python的tarfile和zipfile包完成吧。

6776a1e7c24829ede0554b67cee4f09f.png

源代码

zip转换成gz.tar格式的小脚本,代码比较简单,也就几行,但是写的时候因为绝对路径的问题浪费了点时间,代码水平还是有待提高。话不多说,上代码:

# coding: utf-8import osimport tarfileimport zipfiledef zip2tar(root_path, name, to_name='test'):    '''    root_path: 压缩文件所在根目录    name: 压缩文件名字(zip格式)    '''    # root_path = r'C:甥敳獲AdministratorDesktopsomefiles'    # file_path = os.path.join(root_path, 'somemodel.zip')    file_path = os.path.join(root_path, name + '.zip')with zipfile.ZipFile(file_path, 'r') as zzip:    with tarfile.open(os.path.join(root_path, to_name + '.gz.tar'), 'w') as ttar:        for ffile in zzip.namelist():            if not os.path.isdir(ffile):                # if not ffile.strip().endswith(r'/'):                zzip.extract(ffile, root_path)                ttar.add(os.path.join(root_path, ffile), arcname=ffile)if __name__ == '__main__':    root_path = raw_input(u'input root path: ')    name = raw_input(u'input the zip name(without .zip): ')    zip2tar(root_path, name)

嘿嘿,以后就用这个脚本啦。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值