Python ValueError: embedded null byte

I’m trying to open a .pdf file saved within my DB and then open it with ‘rb’, however, I keep getting an error

Here is a sample of the code I am using.

Fetching the file below:

file = app_tables.quotes.get(quote_number='2-1001')['quote_pdf'].get_bytes()

Opening the file - fails on first line with error (ValueError: embedded null byte):

with open(file, 'rb') as f:
          file_data = f.read()
          file_type = imghdr.what(f.name)
          file_name = str(f.name).split(chr(92))[-1]

I think you want to use io.BytesIO

see: https://docs.python.org/3/library/io.html#io.BytesIO

or: Creating and manipulating pdf files via PyPDF2 and FPDF

from io import BytesIO

file_byte_string = app_tables.quotes.get(quote_number='2-1001')['quote_pdf'].get_bytes()

with BytesIO(file_byte_string ) as f:
          file_data = f.read()
          file_type = imghdr.what(f.name)
          file_name = str(f.name).split(chr(92))[-1]

I am not sure if the rest of your code will actually be able to get a name of a file from a byte string, if you stored your data as a media object it has information about the file like name, type etc.

Thank you, that did work to open the file. However, I failed to mention that I am then adding the file as an email attachment, and as such did not send the file as the correct file type.

I did, however, find a much better way to do what I am looking for with your reminder that I can get the data type and name from anvil. The way I got this working is as such:

msg = EmailMessage()

file = app_tables.quotes.get(quote_number='2-1001')['quote_pdf']

maintype = file.content_type.split('/')[0]
subtype = file.content_type.split('/')[1]
filename = file.name

msg.add_attachment(file.get_bytes(), maintype=maintype, subtype=subtype, filename=filename)
2 Likes