How to Encode and Decode Base64 in Python
A complete, practical tutorial for Python developers. Learn how to securely handle Base64 strings, binary files, and URL-safe encoding using the built-in base64 module.
Python makes working with Base64 incredibly straightforward thanks to its built-in base64 module. You don't need to install any external packages or dependencies—everything you need is right there in the standard library.
Whether you are handling API authentication headers, decoding a JSON Web Token, or processing an email attachment, this guide will show you exactly how to do it.
Quick Note on Bytes vs Strings
In Python 3, the base64 module operates exclusively on bytes-like objects, not standard strings. You must always .encode('utf-8') your strings into bytes before encoding, and .decode('utf-8') the resulting bytes back into strings.
1. Base64 Encode a String in Python
To encode a standard text string into Base64, use the b64encode() method.
import base64
# 1. Start with your plain text string
text = "Hello, Python Base64!"
# 2. Convert the string to bytes
text_bytes = text.encode('utf-8')
# 3. Encode the bytes to Base64
base64_bytes = base64.b64encode(text_bytes)
# 4. Convert the Base64 bytes back to a string for printing/storage
base64_string = base64_bytes.decode('utf-8')
print(f"Encoded string: {base64_string}")
# Output: Encoded string: SGVsbG8sIFB5dGhvbiBCYXNlNjQh2. Base64 Decode a String in Python
If you receive a Base64 string from an API or database, you can decode it using b64decode().
(Tip: If you just want to quickly decode a string without writing code, use our Online Text Converter Tool).
import base64
base64_string = "SGVsbG8sIFB5dGhvbiBCYXNlNjQh"
# 1. Convert the Base64 string to bytes
base64_bytes = base64_string.encode('utf-8')
# 2. Decode the Base64 bytes back to original binary/text bytes
decoded_bytes = base64.b64decode(base64_bytes)
# 3. Convert the original bytes back to a human-readable string
decoded_string = decoded_bytes.decode('utf-8')
print(f"Decoded string: {decoded_string}")
# Output: Decoded string: Hello, Python Base64!3. URL-Safe Base64 Encoding
Standard Base64 contains the + and / characters, which will break URLs if passed as query parameters. Python provides urlsafe_b64encode() specifically for this purpose, which replaces + with - and / with _.
import base64
# A string that will generate problematic characters in standard Base64
data = "subjects?dir=/usr/local&topic=crypto".encode('utf-8')
# Standard encoding (Bad for URLs)
standard = base64.b64encode(data)
print(standard.decode('utf-8'))
# Output: c3ViamVjdHM/ZGlyPS91c3IvbG9jYWwmdG9waWM9Y3J5cHRv
# URL-Safe encoding (Good for URLs)
url_safe = base64.urlsafe_b64encode(data)
print(url_safe.decode('utf-8'))
# Output: c3ViamVjdHM_ZGlyPS91c3IvbG9jYWwmdG9waWM9Y3J5cHRv4. Encoding and Decoding Files (Images, PDFs)
Because Base64 is designed to handle binary data, you don't need to worry about string encoding when working directly with files. You just open the file in binary mode ('rb' or 'wb').
import base64
# --- ENCODING AN IMAGE ---
with open("image.jpg", "rb") as image_file:
# Read the raw binary data from the image
binary_data = image_file.read()
# Encode it to Base64
base64_encoded = base64.b64encode(binary_data)
# Save the Base64 string to a text file
with open("image_base64.txt", "wb") as text_file:
text_file.write(base64_encoded)
print("Image encoded successfully!")
# --- DECODING BACK TO AN IMAGE ---
with open("image_base64.txt", "rb") as text_file:
# Read the Base64 string
base64_data = text_file.read()
# Decode it back to binary
binary_data = base64.b64decode(base64_data)
# Save it as a new image file
with open("restored_image.jpg", "wb") as image_file:
image_file.write(binary_data)
print("Image decoded successfully!")Handling Missing Padding Errors
A very common error in Python is binascii.Error: Incorrect padding. This happens when you try to decode a Base64 string that has had its trailing = signs stripped (which is common in JWTs).
To fix this robustly, you can manually add the padding back before decoding:
import base64
def decode_base64_robust(b64_string):
"""Decodes a Base64 string even if padding is missing."""
# Calculate how much padding is needed
padding_needed = len(b64_string) % 4
if padding_needed:
# Add the necessary '=' characters
b64_string += '=' * (4 - padding_needed)
return base64.b64decode(b64_string)
# A string missing its '==' padding
broken_string = "SGVsbG8gV29ybGQ"
fixed_bytes = decode_base64_robust(broken_string)
print(fixed_bytes.decode('utf-8'))
# Output: Hello WorldDon't feel like writing code?
If you just need to decode a string right now, use our free online utility. It handles padding, URL-safe variants, and file decoding automatically.
Go to the Base64 Converter Tool