Python 3 and base64 encoding of a binary file
Use b64encode
to encode without the newlines and then decode the resulting binary string with .decode('ascii')
to get a normal string.
encodedZip = base64.b64encode(zipContents).decode('ascii')
From the base64 package doc:
base64.encodestring:
"Encode the bytes-like object s, which can contain arbitrary binary data, and return
bytes
containing the base64-encoded data, with newlines (b"\n"
) inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME)."
You want to use
base64.b64encode:
"Encode the bytes-like object s using Base64 and return the encoded
bytes
."
Example:
import base64
with open("test.zip", "rb") as f:
encodedZip = base64.b64encode(f.read())
print(encodedZip.decode())
The decode()
will convert the binary string to text.