python - 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')
作为第二个参数也没有用,我得到了同样的错误。
解决方案
正如我在评论中提到的,问题出在这一行:
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
文档中的参数。
推荐阅读
- python - 如何使用 Jacobian 的有限差分方案获得 minimum_squares 的中间结果
- firebase - 在 Firestore 中设计复杂查询的最佳方法
- go - 如何在 giu imgui 库中创建树形网格?
- javascript - 使用节点 js 按名称过滤
- python - 对函数内的变量使用多个值
- azure - 使用 request.getCookies() 或 request.getSession() 时在 k8s 集群上运行的 Web 应用程序给出 null
- outlook - 无法在 Outlook Web 应用程序中重复出现
- outlook - Outlook 忽略 ics 文件 VEVENT 中的自定义字段
- javascript - Add new Object's name
- eclipse - 使用 eclipse 和 bitbucket 进行 Spring Boot 项目的 Circle CI 集成