Encoding Binary Data as Text

Several kinds of media (e.g., email messages) contain only text. When you want to transmit arbitrary binary data via such media, you need to encode the data as text strings. The Python standard library supplies modules that support the standard encodings known as Base 64, Quoted Printable, and UU.

The base64 Module

The base64 module supports the encoding specified in RFC 1521 as Base 64. The Base 64 encoding is a compact way to represent arbitrary binary data as text, without any attempt to produce human-readable results. Module base64 supplies four functions.

decode

decode(infile,outfile)

Reads text-file-like object infile by calling infile.readline until end of file (i.e., until a call to infile.readline returns an empty string), decodes the Base 64–encoded text thus read, and writes the decoded data to binary-file-like object outfile.

decodestring

decodestring(s)

Decodes text string s, which contains one or more complete lines of Base 64–encoded text, and returns the byte string with the corresponding decoded data.

encode

encode(infile,outfile)

Reads binary-file-like object infile by calling infile.read (for 57 bytes at a time, which is the amount of data that Base 64 encodes into 76 characters in each output line) until end of file (i.e., until a call to infile.read returns an empty string). It encodes the data thus read in Base 64, and writes the encoded text, one line at a time, to text-file-like object outfile, appending \n to each line of text it emits, ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.