user2725109
user2725109

Reputation: 2386

python 2.7 vs 3 encode decode bytes string

The following code runs nicely in Python 2.7

with open(file_path) as ff:
    content = ff.read()
image_bytes_b64=base64.b64encode(content)
function(image_bytes_b64)

It gives me all sorts of errors when I run it in Python 3.6. Do you know what would be the equivalent of the above code in Python 3.6? file_path is the path to a PNG image.

Upvotes: 1

Views: 1010

Answers (2)

Vipin Mohan
Vipin Mohan

Reputation: 1631

open (file_path, 'rb')

Try opening with rb, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

--Edit--

One more change was needed image_bytes_b64=base64.b64encode(content).decode().

Thanks for pointing it out.

To support native Python 2 strings, older Django versions had to accept both bytestrings and unicode strings. Now that Python 2 support is dropped, bytestrings should only be encountered around input/output boundaries (handling of binary fields or HTTP streams, for example).

For bytestrings, this creates a string with an undesired b prefix as well as additional quotes (str(b'foo') is "b'foo'"). To adapt, call decode() on the bytestring before passing it.

Upvotes: 2

mata
mata

Reputation: 69042

Open the file in binary mode then it should work:

with open(file_path, 'rb') as ff:
    content = ff.read()
image_bytes_b64=base64.b64encode(content)
function(image_bytes_b64)

Upvotes: 2

Related Questions