Python base64 module

Overview

Base64 represents binary data using 64 printable characters. It is commonly used to transmit binary data over text-based protocols, to embed resources in JSON/XML/HTML, and in HTTP Basic Auth. The standard alphabet is Aโ€“Z aโ€“z 0โ€“9 + / with padding =; the URL-safe variant replaces + / with - _.

Main APIs (in import base64)

Quick examples

String encode/decode (UTF-8)

import base64

text = "Hello, world"
raw = text.encode("utf-8")

b64 = base64.b64encode(raw)          # bytes
print(b64)                            # b'SGVsbG8sIHdvcmxk'

plain = base64.b64decode(b64)
print(plain.decode("utf-8"))         # Hello, world

URL-safe Base64

import base64

raw = b"token:id/123+scope"
url_b64 = base64.urlsafe_b64encode(raw)
print(url_b64)                        # b'dG9rZW46aWQvMTIzK3Njb3Bl'

print(base64.urlsafe_b64decode(url_b64))  # b'token:id/123+scope'

Strict validation decode

import base64, binascii

try:
	base64.b64decode(b"@@invalid@@", validate=True)
except binascii.Error as exc:
	print("Decode failed:", exc)

File I/O

import base64

# Binary file โ†’ Base64 text
with open("input.bin", "rb") as f:
	encoded = base64.b64encode(f.read()).decode("ascii")
with open("output.txt", "w", encoding="ascii") as f:
	f.write(encoded)

# Base64 text โ†’ binary file
with open("output.txt", "r", encoding="ascii") as f:
	data = base64.b64decode(f.read())
with open("restored.bin", "wb") as f:
	f.write(data)

ASCII85 / Base85

a85encode/a85decode and b85encode/b85decode provide higher density encodings (often used in PostScript and PDF). They accept and return bytes, with options for grouping and compression.

import base64

data = b"hello base85"
a85 = base64.a85encode(data)
b85 = base64.b85encode(data)
print(a85, b85)
print(base64.a85decode(a85))
print(base64.b85decode(b85))

Note: For complete details and edge cases, refer to the official docs at https://docs.python.org/3/library/base64.html.