使用 Python 建立目錄的 Zip 存檔

Vaibhav Vaibhav 2022年5月18日
使用 Python 建立目錄的 Zip 存檔

zip 檔案是一種存檔檔案格式,包含一個或多個壓縮檔案。它支援無損資料壓縮,是全球最常用的存檔格式。本文將幫助我們學習使用 Python 程式語言將目錄轉換為 zip 檔案的方法。

使用 shutil 庫建立目錄的 Zip 存檔

shutil 庫是標準 Python 的一部分。它提供了幾個高階功能來執行檔案或檔案組,例如複製、壓縮、解壓縮和刪除。它有一個名為 make_archive() 的函式或方法,可以將任何目錄或資料夾轉換為 zip 存檔檔案。以下是該函式最常用的引數。

  • base_name:要建立的檔名以及路徑,沒有任何格式副檔名。
  • format:這是存檔格式的名稱。可用選項有 zip(需要 zlib 模組)、targztar(需要 zlib 模組)、bztar(需要 bz2 模組)和 xztar(需要 lzma 模組)。
  • root_dir:該目錄將成為存檔的根目錄,這意味著存檔中的所有路徑都將與其相關。預設值為當前目錄。
  • base_dir:這是存檔開始的目錄。它的值應該相對於 root_dir。預設值為當前目錄。

現在我們已經完成了有關包和所需功能的一些簡要理論,讓我們學習如何使用此功能從目錄建立 zip 存檔。

import os
import shutil

filename = "compressed"
format = "zip"
directory = os.getcwd()
shutil.make_archive(filename, format, directory)

上面的程式碼將當前工作目錄壓縮成一個 zip 檔案,並將檔案命名為 compressed.zip。請注意,我們沒有在 base_name 中提到副檔名 (.zip)。

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

相關文章 - Python Dictionary