How to Decode Base64 Data in Python

Step-by-step guide to decode Base64 data in Python. Handle strings, files, and invalid input easily using the base64 module, no extra packages required.

Base64 converts binary data (like images or files) into ASCII text for safe storage or transmission. In Python, decoding it is simple using the built-in base64 module, no extra installation required.

Methods for Decoding Base64 Data in Python

Here are a few simple and effective ways to decode Base64-encoded strings in Python using built-in modules

1. Basic Base64 String Decoding

Use base64.b64decode() to decode a Base64-encoded string into bytes, and then convert to a readable format.
import base64 # Base64 encoded string (e.g., from an API or file) encoded_data = "SGVsbG8gd29ybGQh" # Decode to bytes decoded_bytes = base64.b64decode(encoded_data) # Convert bytes to string decoded_str = decoded_bytes.decode('utf-8') print(decoded_str) # Output: Hello world!
Note: Always decode bytes to utf-8 (or your desired encoding) if you want human-readable text.

2. Decoding Base64 from a File

If your Base64 data is saved in a file, you can read and decode it easily:
import base64 # Read Base64 string from a file with open("data.txt", "r") as file:     base64_data = file.read() # Decode decoded = base64.b64decode(base64_data) # Optionally write decoded binary to another file with open("output.bin", "wb") as output_file:     output_file.write(decoded)
This is useful when working with encoded images, PDFs, or binary files.
Also Read: How Much Does It Cost To Build A Web App With Python in 2025?

3. Decode and Handle Invalid Input (Safely)

To avoid crashing on invalid Base64 data, use try-except:
import base64 invalid_data = "NotValidBase64===" try:     result = base64.b64decode(invalid_data)     print(result) except Exception as e:     print("Decoding failed:", e)

Tip

When decoding user input or API data, always validate or sanitize it first. Malformed Base64 strings can raise exceptions or security issues if not handled correctly.
Related

Amazon CloudWatch allows you to run log insights queries using the logs client in Boto3. Below is a step by step guide to querying logs…

28 Oct, 2025

The Kalman Filter is an efficient recursive algorithm used to estimate the state of a system from noisy measurements. In computer vision, it’s commonly used…

21 Oct, 2025

Printing exceptions in python helps to debug issues by giving clear information about what went wrong and where. You can access the exception message or…

15 Oct, 2025