Code Example
import base64
# Encode bytes to Base64
data = b'Hello World'
encoded = base64.b64encode(data)
print(encoded) # b'SGVsbG8gV29ybGQ='
# Decode Base64 to bytes
decoded = base64.b64decode(b'SGVsbG8gV29ybGQ=')
print(decoded) # b'Hello World'
# String to Base64
text = 'Hello World'
encoded = base64.b64encode(text.encode('utf-8')).decode('utf-8')
print(encoded) # 'SGVsbG8gV29ybGQ='
# URL-safe Base64 (uses - and _ instead of + and /)
url_safe = base64.urlsafe_b64encode(data)
decoded = base64.urlsafe_b64decode(url_safe)
# Encode file to Base64
with open('image.png', 'rb') as f:
file_data = f.read()
encoded_file = base64.b64encode(file_data).decode('utf-8')
# Decode Base64 to file
with open('output.png', 'wb') as f:
f.write(base64.b64decode(encoded_file))
Key Points: Python base64 module works with bytes. Use .encode()/.decode() for string conversion. urlsafe variants for URL-safe encoding.