Base64 decode in Python: the short version
Python ships a base64 module in the standard library, so there is nothing to install. Decoding is one call:
import base64
data = base64.b64decode("SGVsbG8sIHdvcmxkISDwn5GLIOS9oOWlvQ==")
text = data.decode("utf-8")
print(text) # Hello, world! 👋 你好
b64decode gives you bytes. That is deliberate: Base64 can hold any data, so Python does not guess that it is text. Call .decode("utf-8") only when the original data was UTF-8 text. If you skip that step you will see b'Hello...' instead of the string.
Decode Base64 to a file
When the Base64 holds an image, a PDF or any other file, write the bytes straight to disk instead of turning them into text:
import base64
with open("image.b64", "r") as f:
raw = base64.b64decode(f.read())
with open("image.png", "wb") as out:
out.write(raw)
Open the output file in binary mode ("wb"). If the string starts with a prefix such as data:image/png;base64,, cut everything up to and including the comma first: s.split(",", 1)[1].
URL-safe Base64 and JWTs in Python
Base64URL, used in JWTs and web addresses, swaps + for - and / for _. Python has a matching function:
import base64, json
payload = "eyJ1c2VyIjoiYWRhIiwicm9sZSI6ImFkbWluIn0"
payload += "=" * (-len(payload) % 4) # restore padding
print(json.loads(base64.urlsafe_b64decode(payload)))
# {'user': 'ada', 'role': 'admin'}
The padding line matters. URL-safe strings usually drop the trailing = signs, and Python's decoders refuse a string whose length is not a multiple of four. -len(s) % 4 works out exactly how many are missing.
Common Python Base64 errors
binascii.Error: Incorrect padding. The string is missing = at the end, or it was cut off when copied. Add padding as shown above. If it still fails, the string is incomplete.
UnicodeDecodeError: 'utf-8' codec can't decode byte. Decoding worked, but the bytes are not UTF-8 text. They may be an image, compressed data or text in another encoding such as Latin-1. Paste the string into the decoder at the top of this page: the label above the result tells you what the bytes really are.
Wrong output with no error. By default b64decode silently drops characters outside the Base64 alphabet, including the - and _ of URL-safe strings. Use urlsafe_b64decode for those, and pass validate=True to b64decode when you want bad input to raise an error instead of being ignored:
base64.b64decode(s, validate=True)
Check your result
The fastest way to debug Python Base64 code is to compare it with a known answer. Paste the same string into the Base64 decoder above. If the tool shows readable text but your script fails, the problem is in your padding or alphabet handling. If the tool also says the string is invalid, the input itself is broken.
For the same task in the browser or Node.js, see Base64 decode in JavaScript. For everything else, use the online Base64 decoder.
Last updated: