使用Python壓縮和解壓縮zip檔案的教程

來源:互聯網
上載者:User
python 的 zipfile 提供了非常便捷的方法來壓縮和解壓 zip 檔案。

例如,在py指令碼所在目錄中,有如下檔案:

複製代碼 代碼如下:

readability/readability.js
readability/readability.txt
readability/readability-print.css
readability/sprite-readability.png
readability/readability.css

將 readability 目錄中的檔案壓縮到指令碼所在目錄的 readability.zip 檔案中,保持相同的檔案結構,然後列印出產生的壓縮包 的檔案清單,再用兩種方式分別解壓檔案到指令碼所在目錄的 output 目錄和 output/bak 目錄中。

指令碼如下:

#!/usr/vin/env python# coding: utf-8"""壓縮和解壓zip檔案"""import osimport zipfiledef compress(zip_file, input_dir):  f_zip = zipfile.ZipFile(zip_file, 'w')  for root, dirs, files in os.walk(input_dir):    for f in files:      # 擷取檔案相對路徑,在壓縮包內建立相同的目錄結構      abs_path = os.path.join(os.path.join(root, f))      rel_path = os.path.relpath(abs_path, os.path.dirname(input_dir))      f_zip.write(abs_path, rel_path, zipfile.ZIP_STORED)def extract(zip_file, output_dir):  f_zip = zipfile.ZipFile(zip_file, 'r')  # 解壓所有檔案到指定目錄  f_zip.extractall(output_dir)  # 逐個解壓檔案到指定目錄  for f in f_zip.namelist():    f_zip.extract(f, os.path.join(output_dir, 'bak'))def printdir(zip_file):  f_zip = zipfile.ZipFile(zip_file, 'r')  print '== printdir() ============================'  f_zip.printdir()  print  print '== namelist() ============================'  for f in f_zip.namelist():    print fif __name__ == '__main__':  zip_file = 'readability.zip'  compress(zip_file, os.path.join(os.getcwd(), 'readability'))  printdirzip_file)  extract(zip_file, 'output')
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.