专业的编程技术博客社区

网站首页 > 博客文章 正文

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

baijin 2024-09-05 11:18:46 博客文章 4 ℃ 0 评论

起因

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

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

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

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

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

源代码

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

# coding: utf-8

import os
import tarfile
import zipfile


def zip2tar(root_path, name, to_name='test'):
    '''
    root_path: 压缩文件所在根目录
    name: 压缩文件名字(zip格式)
    '''
    # root_path = r'C:\Users\Administrator\Desktop\somefiles'
    # 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)

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

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表