【问题标题】:Zip file to bytes Python 3压缩文件到字节 Python 3
【发布时间】:2019-02-25 18:29:21
【问题描述】:

我想在 postgres 数据库中存储一个 zip 文件。列类型为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-1ISO-8859-1,这两个都给我一个错误。

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

关于如何获取 zip 文件的字节以便我可以将其存储在 postgres 数据库中的任何想法?

【问题讨论】:

    标签: excel python-3.x postgresql zipfile


    【解决方案1】:

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

    with open(filename, 'rb') as file_data:
        bytes_content = file_data.read()
    

    【讨论】:

    • 我认为 'rb' 在 python 3 中不再允许。这行得通。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多