Python’s standard library module base64 covers standard Base64, Base64URL, Base32, Base16 and Ascii85. Its functions take and return bytes, which is the first thing to remember.
Encode a string
import base64
encoded = base64.b64encode("Grüße 👋".encode("utf-8"))
print(encoded) # b'R3LDvMOfZSDwn5GL'
print(encoded.decode()) # 'R3LDvMOfZSDwn5GL' (str)
Passing a str directly raises TypeError: a bytes-like object is required, not 'str'.
Decode to a string
text = base64.b64decode("R3LDvMOfZSDwn5GL").decode("utf-8")
b64decode accepts both str (ASCII only) and bytes.
Strict validation
By default b64decode silently discards characters outside the alphabet. Pass validate=True to reject them:
import binascii
try:
data = base64.b64decode(value, validate=True)
except binascii.Error as e:
print("Invalid Base64:", e)
“Incorrect padding” error
binascii.Error: Incorrect padding means the length is not a multiple of 4. This is common with Base64URL values from JWTs or URLs, which omit =. Restore the padding:
def b64decode_nopad(s: str) -> bytes:
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
Base64URL
base64.urlsafe_b64encode(b"\xfb\xff").decode() # '-_8='
base64.urlsafe_b64encode(data).rstrip(b"=") # without padding
Files and images
from pathlib import Path
b64 = base64.b64encode(Path("logo.png").read_bytes()).decode()
data_uri = f"data:image/png;base64,{b64}"
Path("restored.png").write_bytes(base64.b64decode(b64))
For very large files use base64.encode(infile, outfile), which streams and wraps lines at 76 characters (MIME style).
Line breaks
b64encode never adds line breaks. base64.encodebytes() inserts a newline every 76 characters, as required by e-mail (MIME). b64decode ignores newlines only when validate=False.
Command line
python3 -m base64 file.bin # encode
python3 -m base64 -d file.b64 # decode
Verify your output with the Base64 decoder or check the value with the validator.
टिप्पणियाँ (0)
“Base64 in Python” के बारे में कोई सवाल, सुझाव या बग? टिप्पणी करें, टूल को रेटिंग दें, या दूसरों को जवाब दें।
अभी तक कोई टिप्पणी नहीं। अपनी राय देने वाले पहले व्यक्ति बनें!