python method of converting zip to ES2en.tar

  • 2020-12-22 17:43:29
  • OfStack

With no direct colleagues computer can compress gz. tar format compression software, and work in this often need to convert zip file to gz. tar format, so often will be compressed into zip format file to me to be compressed into gz. tar format sent him, can be lazy don't want to begin, will be finished with python tarfile and zipfile bag 1 converting zip gz. tar format small script:

The code is relatively simple, only a few lines long, but at the time of writing it was a bit of a waste of time because of the absolute path problem, and the level of the code still needs to be improved.


#coding: utf-8

import os
import tarfile
import zipfile

def zip2tar(root_path, name,to_name='test'):

 '''
 root_path:  Zip files in the root directory 
 name :   Compressed file name ( zip Format) 
 '''
 #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)

Related articles: