将 python 中的 zip 文件保存到磁盘

Saving zip file in python to disk

我在数据库中有一个 bytea 对象,它是一个 zip 文件,我可以检索它并以 zip 文件的形式读取它,但我也想将它保存到磁盘。

我不知道如何将 zf_model 写入磁盘。我也试过 zf.write(io.BytesIO(model.model_file)),即不先转换为 zip,但这也不起作用。

这是我试过的:

from zipfile import ZipFile
from io import BytesIO
        
#Retrieve the zip file from database (zip file is in a field called model_file for object: Model)
model = Model().query.filter_by(param = "test").first()
#convert the retrieved object to a zip file
zf_model = ZipFile(BytesIO(model.model_file), "w")
    
tempfile = "/tmp/test.zip"

with zipfile.ZipFile(tempfile, "w", compression=zipfile.ZIP_DEFLATED) as zf:
    zf.write(zf_model)

给出错误:

TypeError: a bytes-like object is required, not 'ZipFile'

尝试直接写入 bytea 对象

with open(tempfile, 'w+') as f:
    f.write(model.model_file)      

给出错误:

TypeError: write() argument must be str, not bytes

如果您从数据库中检索已经压缩的文件,您可以根本不使用 ZipFile 将其写入磁盘。

#Retrieve the zip file from database (zip file is in a field called model_file for object: Model)
model = Model().query.filter_by(param = "test").first()

tempfile = "/tmp/test.zip"

with open(tempfile, 'wb') as f:
    f.write(model.model_file)

无论如何,如果您的模型存储纯字节数据(不是压缩数据),您可以执行以下操作

from zipfile import ZipFile

#Retrieve the zip file from database 
model = Model().query.filter_by(param = "test").first()

tempfile = "/tmp/test.zip"

with ZipFile(tempfile, 'w') as f:
    f.writestr('name_of_file_in_zip_archive.txt', model.model_file)