all Python 3base64function
base64.encode()
legacy interface
Legacy interface: reads a binary file and writes Base64 to another file in lines of 76 characters, as in MIME.
Syntax
base64.encode(input, output)
Both files must be opened in binary mode ('rb' and 'wb'): a text file gives TypeError. The output has a newline after every 76 characters plus one at the end, so it is not the single line b64encode gives. For data held in memory it is awkward; b64encode is simpler.
Examples
import base64
with open('data.bin', 'wb') as f:
f.write(b'x' * 60)
with open('data.bin', 'rb') as src, open('data.b64', 'wb') as dst:
base64.encode(src, dst)
with open('data.b64', 'rb') as f:
print(f.read().count(b'\n')) # → 2
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy