Python 建立 zip 壓縮檔可以透過 zipfile 模組, zipfile 模組提供了關於 zip 壓縮檔的功能.
使用 zipfile 模組建立 zip 壓縮檔, 需要經過以下 3 個步驟:
建立 ZipFile 物件, 這時設定 zip 檔的檔案名稱, 及設定成 “w” 模式 (write mode).
呼叫 write() 加入檔案.
呼叫 close() 關閉檔案.
以下是一個簡單的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from zipfile import ZipFile # create ZipFile object zip_fp = ZipFile('my-archives.zip', 'w') # Add files to the zip zip_fp.write('file1.log') zip_fp.write('file2.log') zip_fp.write('file3.log') # close the Zip File zip_fp.close() |
上面的程式碼會建立 my-archives.zip 檔案, 裡面會放入檔案 file1.log, file2.log 及 file3.log.
如果要將整個目錄壓縮, 需要將整個目錄讀取一次, 包括裡面的副目錄, 然後逐個檔案加入 zip 檔:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#!/usr/bin/python from zipfile import ZipFile import os from os.path import basename dir_name = "/path/to/zip/" # create a ZipFile object with ZipFile('my-archives.zip', 'w') as zip_fp: # real all items in directory for folder_name, subfolders, filenames in os.walk(dir_name): for filename in filenames: # create file's path in directory filePath = os.path.join(folder_name, filename) # Add file to zip zip_fp.write(filePath, basename(filePath)) |
以上是 Python 建立 zip 壓縮檔的簡單例子, 可以按需要加入不同的功能。