0

Reading bytes gives conflicting results

    bytes_file = BytesIO(requests.get(source_url).content)

    accepted_start_bytes = {
    "jpeg": b'\xFF\xD8\xFF',
    "png":  b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A',
    }


    print( bytes_file.read().startswith(accepted_start_bytes['jpeg']))

    print( [bytes_file.read().startswith(accepted_start_bytes['jpeg'])])

has the output of

>>> True
>>> False

I would think these should be the same...

Seb Kelly
  • 81
  • 1
  • 9

1 Answers1

1

I found the solution. Turns out that you need to seek the zero position of the file before you read it, due to how the file is read.

The code should be

bytes_file = BytesIO(requests.get(source_url).content)

accepted_start_bytes = {
"jpeg": b'\xFF\xD8\xFF',
"png":  b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A',
}

bytes_file.seek(0)
print( bytes_file.read().startswith(accepted_start_bytes['jpeg']))
bytes_file.seek(0)
print( [bytes_file.read().startswith(accepted_start_bytes['jpeg'])])

This gets a result of

>>> True
>>> True
Seb Kelly
  • 81
  • 1
  • 9