将文件压缩为字节数Python 3 [英] Zip file to bytes Python 3
问题描述
我想将一个zip文件存储在postgres数据库中.列的类型为 bytea
I want to store a zip file in a postgres database. The column is type bytea
当尝试获取json文件或csv文件的字节时,我可以使用此
When attempting to get the bytes of a json file, or a csv file I can use this
with open(filename, encoding='utf-8') as file_data:
bytes_content = file_data.read()
但是,如果我尝试使用zip文件或什至xls文件,则会收到错误消息.
However, if I try a zip file, or even an xls file I get an error.
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd7 in position 14: invalid continuation byte
我进行了一些搜索,并建议更改为编码类型,我尝试了 latin-1
和 ISO-8859-1
,两者都给了我一个错误.
I did some searching and it was suggested to change to encoding type, I've tried latin-1
and ISO-8859-1
, both of which gives me an error.
ValueError: A string literal cannot contain NUL (0x00) characters.
关于如何获取zip文件的字节的任何想法,以便我可以将其存储在postgres数据库中吗?
Any idea as to how to get the bytes of a zip file so I can store it in a postgres database?
推荐答案
如果要将JSON文件读取为字节,则应以二进制模式打开文件:
If you want to read the JSON file as bytes you should open the file in binary mode:
with open(filename, 'rb') as file_data:
bytes_content = file_data.read()
这篇关于将文件压缩为字节数Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!