将zip文件转换为字节(Python 3)

6

我想将一个zip文件存储在Postgres数据库中。该列的类型是bytea

当尝试获取JSON文件或CSV文件的字节时,可以使用以下方法:

with open(filename, encoding='utf-8') as file_data:
    bytes_content = file_data.read()

但是,如果我尝试压缩文件或者xls文件,就会出现错误。

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd7 in position 14: invalid continuation byte

我进行了一些搜索,建议更改编码类型,我尝试了latin-1ISO-8859-1,但都导致错误。

ValueError: A string literal cannot contain NUL (0x00) characters.

有想法如何获取zip文件的字节,以便将其存储在postgres数据库中吗?
1个回答

10
如果您希望以字节形式读取JSON文件,则应以二进制模式打开该文件:
with open(filename, 'rb') as file_data:
    bytes_content = file_data.read()

1
我以为在Python 3中不再允许使用'rb'。但是它确实可以工作。谢谢! - Gabriel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接