Base64 Encoding in Python

Python's base64 module provides functions for encoding and decoding Base64.

Basic Usage

Encode to Base64

import base64

text = "Hello, World!"
encoded = base64.b64encode(text.encode('utf-8'))
print(encoded.decode('utf-8'))  # "SGVsbG8sIFdvcmxkIQ=="

Decode from Base64

import base64

encoded = "SGVsbG8sIFdvcmxkIQ=="
decoded = base64.b64decode(encoded)
print(decoded.decode('utf-8'))  # "Hello, World!"

URL-Safe Base64

Use urlsafe_b64encode and urlsafe_b64decode for URL-safe encoding:

import base64

text = "Hello, World!"
encoded = base64.urlsafe_b64encode(text.encode('utf-8'))
print(encoded.decode('utf-8'))  # "SGVsbG8sIFdvcmxkIQ=="

decoded = base64.urlsafe_b64decode(encoded)
print(decoded.decode('utf-8'))  # "Hello, World!"

File to Base64

Encode a File

import base64

with open('image.png', 'rb') as f:
    encoded = base64.b64encode(f.read())
    print(encoded.decode('utf-8'))

Decode to File

import base64

encoded = "iVBORw0KGgo..."  # Base64 string

with open('output.png', 'wb') as f:
    f.write(base64.b64decode(encoded))

One-Liner

Quick encoding/decoding in terminal:

# Encode
python -c "import base64; print(base64.b64encode(b'Hello').decode())"

# Decode
python -c "import base64; print(base64.b64decode('SGVsbG8=').decode())"

Data URL

Create a Data URL from a file:

import base64
import mimetypes

def file_to_data_url(filepath):
    mime_type = mimetypes.guess_type(filepath)[0] or 'application/octet-stream'
    with open(filepath, 'rb') as f:
        encoded = base64.b64encode(f.read()).decode('utf-8')
    return f"data:{mime_type};base64,{encoded}"

print(file_to_data_url('image.png'))

Handling Padding

Add missing padding to Base64 strings:

import base64

def decode_with_padding(data):
    # Add padding if needed
    padding = 4 - len(data) % 4
    if padding != 4:
        data += '=' * padding
    return base64.b64decode(data)

# Works with or without padding
print(decode_with_padding('SGVsbG8').decode())  # "Hello"
print(decode_with_padding('SGVsbG8=').decode())  # "Hello"