Skip to main content

Base64 Encoding in Python: Complete Tutorial

Learn Base64 encoding in Python using the base64 module. Examples for b64encode, b64decode, URL-safe encoding, and file encoding.

How to Base64 Encode in Python

Python's built-in base64 module provides functions for encoding and decoding binary data using Base64, Base32, Base16, and other schemes. The module handles all the padding and character-set details automatically.

Basic Encoding and Decoding

import base64

# Encode a string to Base64 (must be bytes)
encoded = base64.b64encode(b\"Hello, World!\")
print(encoded)  # b'SGVsbG8sIFdvcmxkIQ=='
print(encoded.decode(\"ascii\"))  # SGVsbG8sIFdvcmxkIQ==

# Decode from Base64
decoded = base64.b64decode(b\"SGVsbG8sIFdvcmxkIQ==\")
print(decoded)  # b'Hello, World!'
print(decoded.decode(\"utf-8\"))  # Hello, World!

URL-Safe Base64 Encoding

Standard Base64 uses + and / characters which are special in URLs. Use urlsafe_b64encode() to replace them with - and _:

import base64

data = b\"subjects?_d=1&page=2\"
standard = base64.b64encode(data)
url_safe = base64.urlsafe_b64encode(data)

print(standard)   # Contains + and / characters
print(url_safe)    # Uses - and _ instead (safe for URLs)

Encoding Files

import base64

# Encode an image file
with open(\"photo.png\", \"rb\") as f:
    encoded = base64.b64encode(f.read())

# Create a data URI
data_uri = f\"data:image/png;base64,{encoded.decode('ascii')}\"

# Decode and save back to file
with open(\"output.png\", \"wb\") as f:
    f.write(base64.b64decode(encoded))

Streaming Large Files

For large files, avoid loading the entire file into memory. Use chunked encoding:

import base64

def encode_file_chunked(input_path, output_path, chunk_size=57):
    \"\"\"Encode a file in chunks. chunk_size=57 produces 76-char Base64 lines.\"\"\"
    with open(input_path, \"rb\") as fin, open(output_path, \"w\") as fout:
        while chunk := fin.read(chunk_size):
            fout.write(base64.b64encode(chunk).decode(\"ascii\"))
            fout.write(\"\
\")

Common Use Cases in Python

  • Email attachments — MIME encoding uses Base64 for binary attachments via email.mime
  • API authentication — HTTP Basic Auth encodes credentials as Base64
  • JSON serialization — binary data embedded in JSON payloads
  • Data URIs — embedding images in HTML templates generated by Flask or Django
  • Cryptography — encoding keys and certificates in PEM format

Try Base64 Encoder/Decoder Free

Encode and decode Base64 strings.

Use Base64 Encoder/Decoder →