Python base64 encode














































Python base64 encode



Python base64 Encode METHOD

Encode method is a part of python's Lib/base64.py module. This module provides functionality for encoding binary data to printable ASCII characters and decoding such encodings back to binary, read more about the module here. There are two interfaces provided by this module. Encode method is a part of legacy interface. The legacy interface does not allow decoding from strings, but do support functions for encoding and decoding to and from file objects.

encode(input,output)

Arguments

input = Binary file object of input file

output = Binary file object of output file

Description

This method reads the binary input file, encode it and writes back the encoded data to the output file. Input file is read until MAXBINSIZE where it is calculated as follows.
MAXLINESIZE = 76 # Excluding the CRLF
MAXBINSIZE = (MAXLINESIZE//4)*3

Also encode() method appends a newline character (b'\n') after every 76 bytes and a trailing newline. The binascii.b2a_base64() method is used to convert binary data to a line of ASCII characters in base64 encoding in the encode method functionality.

Limitations

  • Input and output should be file objects
  • Input and output file objects should be opened in binary mode

Usage

>>> import base64

>>> a = open("input.txt","rb")
>>> b = open("output.txt","wb")
>>> base64.encode(a,b)
>>> a.close()
>>> b.close()
input.txt
This is a test input string.
output.txt
VGhpcyBpcyBhIHRlc3QgaW5wdXQgc3RyaW5nLgo=

Note

If binary mode isn't used while opening input file the following error will occur
TypeError: a bytes-like object is required, not 'str'
If binary mode isn't used while opening output file the following error will occur
TypeError: write() argument must be str, not bytes
If no input is provided as an argument the following error will occur
TypeError: encode() missing 2 required positional arguments: 'input' and 'output'

Comments