Base64 Encoding in Python
Learn Base64 encoding and decoding in Python using the base64 module. Handle strings, bytes, and files.
base64 pythonpython encode base64base64 module pythonpython base64 stringpython base64 file
Python's base64 module provides simple functions for encoding and decoding Base64 data.
Basic Encoding/Decoding
import base64; base64.b64encode(b"hello") to encode, base64.b64decode(encoded) to decode. Remember to use bytes, not strings.
Encoding Files
Read file in binary mode: with open("file", "rb") as f: encoded = base64.b64encode(f.read())
URL-Safe Base64
Use base64.urlsafe_b64encode() for URL-safe encoding, which replaces + with - and / with _ for use in URLs.
Summary
Verify your Python Base64 output with our online encoder/decoder.