将 Zip 文件转换为字节 Python 3

2024-04-17

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

当尝试获取 json 文件或 csv 文件的字节时,我可以使用这个

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

但是,如果我尝试使用 zip 文件,甚至 xls 文件,则会出现错误。

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

我做了一些搜索,建议更改为编码类型,我已经尝试过latin-1 and ISO-8859-1,这两个都给我一个错误。

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

知道如何获取 zip 文件的字节以便将其存储在 postgres 数据库中吗?


如果您想以字节形式读取 JSON 文件,您应该以二进制模式打开该文件:

with open(filename, 'rb') as file_data:
    bytes_content = file_data.read()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Zip 文件转换为字节 Python 3 的相关文章

随机推荐