专业编程基础技术教程

网站首页 > 基础教程 正文

python使用zip压缩目录及相关问题

ccvgpt 2024-08-06 12:40:11 基础教程 14 ℃

一、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可以压缩成过大文件。

最近发表
标签列表