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 压缩档的简单例子, 可以按需要加入不同的功能。