zipfile 压缩普通文件文件
zip_file = zipfile.ZipFile("/tmp/2.zip", 'a', zipfile.ZIP_DEFLATED, False) zip_file.write("/tmp/6be69f6eb16c4aa1a8c861018f1a91fe.jpeg", arcname="6be69f6eb16c4aa1a8c861018f1a91fe.jpeg")
zip_file.close()
zip file直接压缩文件流
import requests url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1114%2F062021132H5%2F210620132H5-1-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659686331&t=ece44f08d7087af79904764edb9ea7dc" zipFile = zipfile.ZipFile("/tmp/3333.zip", 'w') res = requests.get(url) data = res.content zipFile.writestr("1234.jpg", data, zipfile.ZIP_DEFLATED)
zip file 文件直接压缩到内存中
'''文件压缩到内存中''' stream = io.BytesIO() zfile = zipfile.ZipFile(stream, 'w', zipfile.ZIP_DEFLATED, allowZip64=False) for i in files: if os.path.isfile(i): zfile.write(i, os.path.basename(i)) zfile.close() stream.seek(0) print(stream) # 文件流