由于同事電腦上沒有直接可以壓縮gz.tar格式的壓縮軟件,而工作中這個又時常需要將zip文件轉換為gz.tar格式,所以常常將壓縮為zip格式的文件發(fā)給我來重新壓縮成gz.tar格式發(fā)給他,能偷懶就不想動手,就用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:/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)
以上這篇python中將zip壓縮包轉為gz.tar的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答