Python打包檔案夾的方法小結(zip,tar,tar.gz等)

來源:互聯網
上載者:User

標籤:wal   演算法   打包   containe   func   art   out   根目錄   教程   

本文執行個體講述了Python打包檔案夾的方法。分享給大家供大家參考,具體如下:

一、zip

?
1234567891011 import os, zipfile#打包目錄為zip檔案(未壓縮)def make_zip(source_dir, output_filename):  zipf = zipfile.ZipFile(output_filename, ‘w‘)  pre_len = len(os.path.dirname(source_dir))  for parent, dirnames, filenames in os.walk(source_dir):    for filename in filenames:      pathfile = os.path.join(parent, filename)      arcname = pathfile[pre_len:].strip(os.path.sep)   #相對路徑      zipf.write(pathfile, arcname)  zipf.close()

二、tar/tar.gz

?
123456789101112131415 import os, tarfile#一次性打包整個根目錄。空子目錄會被打包。#如果只打包不壓縮,將"w:gz"參數改為"w:"或"w"即可。def make_targz(output_filename, source_dir):  with tarfile.open(output_filename, "w:gz") as tar:    tar.add(source_dir, arcname=os.path.basename(source_dir))#逐個添加檔案打包,未打包空子目錄。可過濾檔案。#如果只打包不壓縮,將"w:gz"參數改為"w:"或"w"即可。def make_targz_one_by_one(output_filename, source_dir):  tar = tarfile.open(output_filename,"w:gz")  for root,dir,files in os.walk(source_dir):    for file in files:      pathfile = os.path.join(root, file)      tar.add(pathfile)  tar.close()

更多關於Python相關內容感興趣的讀者可查看本站專題:《Python檔案與目錄操作技巧匯總》、《Python文字檔操作技巧匯總》、《Python URL操作技巧總結》、《Python圖片操作技巧總結》、《Python資料結構與演算法教程》、《Python Socket編程技巧總結》、《Python函數提示總結》、《Python字串操作技巧匯總》及《Python入門與進階經典教程》

Python打包檔案夾的方法小結(zip,tar,tar.gz等)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.