Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip file to bytes Python 3

I want to store a zip file in a postgres database. The column is type bytea

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()

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

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.

Any idea as to how to get the bytes of a zip file so I can store it in a postgres database?

like image 999
Gabriel Avatar asked Mar 05 '23 10:03

Gabriel


1 Answers

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()
like image 149
blhsing Avatar answered Mar 11 '23 14:03

blhsing