python zip 压缩文件 解压文件
# 压缩文件 import errno import os import zipfile def zip_pack_file(target_path, zip_file_name=None): # target_path 目标路径 # 要压缩成的文件名路径 if zip_file_name is None: zip_file_name = target_path.split("/")[-1] + ".zip" base_dir = os.path.dirname(target_path) if os.path.isfile(target_path): # zip_file_name 文件名路径,a是追加,w是写入,会覆盖 with zipfile.ZipFile(zip_file_name, "a") as zipfile_client: zipfile_client.write(zip_file_name, arcname=zip_file_name.replace(base_dir, ""), compress_type=zipfile.ZIP_DEFLATED) elif os.path.isdir(target_path): with zipfile.ZipFile(zip_file_name, "a") as zip_file: for dirpath, dirnames, filenames in os.walk(target_path): for filename in filenames: target_file = os.path.join(dirpath, filename) zip_file.write(target_file, arcname=target_file.replace(base_dir, ""), compress_type=zipfile.ZIP_DEFLATED) else: raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), target_path) print("Created zip file : {}".format(zip_file_name))
解压文件
import zipfile def unzip_file(zip_file,target="."): # 要解压的文件,目标路径 with zipfile.ZipFile(zip_file) as zipfile_client: zip_list = zipfileclient.namelist() for f in zip_list: zip_file.extract(f, target)