繁体   English   中英

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

[英]Saving zip file in python to disk

我在数据库中有一个bytea object,它是一个 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 object

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)

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM