Base64 使用 64 个可打印字符表示二进制数据,常用于基于文本的传输协议、在 JSON/XML/HTML 中内嵌资源,
以及 HTTP Basic 认证等场景。标准字母表为 A–Z a–z 0–9 + /,使用 = 作为填充;
URL 安全变体用 - _ 替代 + /。
import base64)b64encode(data: bytes, altchars: bytes | None = None) -> bytesb64decode(data: bytes | str, altchars: bytes | None = None, validate: bool = False) -> bytesstandard_b64encode / standard_b64decode (force the standard alphabet)urlsafe_b64encode / urlsafe_b64decode (URL/filename-safe variant)b32encode / b32decode, b16encode / b16decodea85encode / a85decode, b85encode / b85decode (ASCII85/Base85)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
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'
import base64, binascii
try:
base64.b64decode(b"@@invalid@@", validate=True)
except binascii.Error as exc:
print("Decode failed:", exc)
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)
a85encode/a85decode 与 b85encode/b85decode 提供更高密度的编码(常见于 PostScript 与 PDF),
接收与返回的均为 bytes,并可配置分组与压缩等选项。
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))
提示:更多细节与边界情况请参考官方文档:
https://docs.python.org/3/library/base64.html。