May 2001
Intermediate to advanced
304 pages
6h 12m
English
The base64 encoding scheme is used to convert
arbitrary binary data to plain text. To do this, the encoder stores
each group of three binary bytes as a group of four characters from
the following set:
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789+/
In addition, the = character is used for padding at
the end of the data stream.
Example 4-18 shows how the encode and decode
functions work on file objects.
Example 4-18. Using the base64 Module to Encode Files
File: base64-example-1.py
import base64
MESSAGE = "life of brian"
file = open("out.txt", "w")
file.write(MESSAGE)
file.close()
base64.encode(open("out.txt"), open("out.b64", "w"))
base64.decode(open("out.b64"), open("out.txt", "w"))
print "original:", repr(MESSAGE)
print "encoded message:", repr(open("out.b64").read())
print "decoded message:", repr(open("out.txt").read())
original: 'life of brian'
encoded message: 'bGlmZSBvZiBicmlhbg==\012'
decoded message: 'life of brian'
Example 4-19 shows the encodestring and
decodestring functions converting between strings. The functions are currently implemented as wrappers on top of
encode and decode, using
StringIO objects for input and output.
Example 4-19. Using the base64 Module to Encode Strings
File: base64-example-2.py import base64 MESSAGE = "life of brian" data = base64.encodestring(MESSAGE) original_data = base64.decodestring(data) print "original:", repr(MESSAGE) print "encoded data:", repr(data) print "decoded data:", repr(original_data) ...
Read now
Unlock full access