起因
老大:阿毛你把项目调研结果压缩为gz.tar文件发我一下,老总要看一下。。。
阿毛:老大zip文件可以吗?
老大:你把zip文件转换一下就OK了,什么???你电脑上没有可以压缩gz.tar格式的压缩软件???
阿毛:反思中。。。工作中这个又时常需要将zip文件转换为gz.tar格式,所以常常将压缩为zip格式的文件来重新压缩成gz.tar格式发给他。
装一下压缩软件吧???还不想把电脑弄的乱七八糟的应用。能偷懒就不想动手,灵机一动,那就用python的tarfile和zipfile包完成吧。
源代码
zip转换成gz.tar格式的小脚本,代码比较简单,也就几行,但是写的时候因为绝对路径的问题浪费了点时间,代码水平还是有待提高。话不多说,上代码:
# coding: utf-8import osimport tarfileimport zipfiledef zip2tar(root_path, name, to_name='test'): ''' root_path: 压缩文件所在根目录 name: 压缩文件名字(zip格式) ''' # root_path = r'C:UsersAdministratorDesktopsomefiles' # 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)
嘿嘿,以后就用这个脚本啦。。。
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!