python使用zip壓縮目錄及相關問題

一、Python封裝的使用zip壓縮文件的代碼(修正版):

說明:這個函數只是針對性地壓縮一個目錄下所有文件,若使用,你可能需要再修改。

作用:壓縮目錄並返回壓縮文件路徑。

參數:

zip_filename str: 壓縮文件名,包含後綴.zip

zip_path str: 壓縮目錄,程序要能探查到目錄,比如可以用絕對路徑;或者相對路徑,但是要切換到同目錄下

exclude list: 依據後綴要排除的文件,參考使用中的例子

使用:

zipfilepath = make_zipfile("test.zip", "testdir", [".zip", ".lock"])

以上代碼運行的當前目錄存在testdir目錄,將會逐一壓縮testdir目錄下的文件,文件後綴包含.zip、.lock的將不壓縮。

代碼:

def make_zipfile(zip_filename, zip_path, exclude=[]):
"""Create a zipped file with the name zip_filename. Compress the files in the zip_path directory. Do not include subdirectories. Exclude files in the exclude file.
@param zip_filename str: Compressed file name
@param zip_path str: The compressed directory (the files in this directory will be compressed)
@param exclude list,tuple: File suffixes will not be compressed in this list when compressed
"""
if zip_filename and os.path.splitext(zip_filename)[-1] == ".zip" and zip_path and os.path.isdir(zip_path) and isinstance(exclude, (list, tuple)):
try:
import zipfile
except ImportError:
raise
with zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as zf:
for filename in os.listdir(zip_path):
if os.path.isdir(filename):
continue
if not os.path.splitext(filename)[-1] in exclude:
zf.write(os.path.join(zip_path, filename), filename)
return zip_filename if os.path.isabs(zip_filename) else os.path.join(os.getcwd(), zip_filename)

else:
raise TypeError

二、遇到的問題:

1. LargeZipFile: Zipfile size would require ZIP64 extensions

答:參加上述代碼,allowZip64=True在這個問題發生時是沒有的,由於壓縮容量過大,發生異常,此時需要允許zip64,這個參數默認是False,改為True可以壓縮成過大文件。


分享到:


相關文章: