首页 > 解决方案 > Python3.6 的 Zipfile 模块:写入字节而不是 Odoo 的文件

问题描述


我一直在尝试使用 Python 3.6 的 zipfile 模块来创建一个包含多个对象的 .zip 文件。
我的问题是,我必须管理 Odoo 数据库中的文件,该数据库只允许我使用bytes对象而不是文件。

这是我当前的代码:

import zipfile

empty_zip_data = b'PK\x05\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
zip = zipfile.ZipFile(empty_zip_data, 'w')

# files is a list of tuples: [(u'file_name', b'file_data'), ...]
for file in files:
    file_name = file[0]
    file_data = file[1]
    zip.writestr(file_name, file_data)

返回此错误:

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/zipfile.py", line 1658, in writestr
  with self.open(zinfo, mode='w') as dest:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/zipfile.py", line 1355, in open
  return self._open_to_write(zinfo, force_zip64=force_zip64)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/zipfile.py", line 1468, in _open_to_write
  self.fp.write(zinfo.FileHeader(zip64))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/zipfile.py", line 723, in write
  n = self.fp.write(data)
AttributeError: 'bytes' object has no attribute 'write'

我该怎么做?我遵循了ZipFile.writestr() 文档,但这让我无处可去……

编辑:使用file_data = file[1].decode('utf-8')作为第二个参数也没有用,我得到了同样的错误。

标签: pythonodoozipfilevirtual-memory

解决方案


正如我在评论中提到的,问题出在这一行:

empty_zip_data = b'PK\x05\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
zip = zipfile.ZipFile(empty_zip_data, 'w')

您正在尝试将一个byte对象传递给该ZipFile()方法,但就像open()它期望一个类似路径的对象一样。

在您的情况下,您可能想要使用该tempfile模块(在此特定示例中,我们将使用SpooledTemporaryFile相关问题

import tempfile
import zipfile

# Create a virtual temp file
with tempfile.SpooledTemporaryFile() as tp:

    # pass the temp file for zip File to open
    with zipfile.ZipFile(tp, 'w') as zip:
        files = [(u'file_name', b'file_data'), (u'file_name2', b'file_data2'),]
        for file in files:
            file_name = file[0]
            file_data = file[1]
            zip.writestr(file_name, file_data)

    # Reset the cursor back to beginning of the temp file
    tp.seek(0)
    zipped_bytes = tp.read()

zipped_bytes
# b'PK\x03\x04\x14\x00\x00\x00\x00\x00\xa8U ... \x00\x00'

请注意使用上下文管理器来确保所有文件对象在加载后都正确关闭。

这为您提供zipped_bytes了您想要传递回 Odoo 的字节。您还可以zipped_bytes通过将其写入物理文件来测试它,以首先查看它的外观:

with open('test.zip', 'wb') as zf:
    zf.write(zipped_bytes)

如果您正在处理相当大的文件大小,请务必注意并使用max_size文档中的参数。


推荐阅读