0
0
PythonHow-ToBeginner · 3 min read

How to Read Binary File in Python: Simple Guide

To read a binary file in Python, use the open() function with the mode set to 'rb' (read binary). Then, use methods like read() to get the binary data as bytes.
📐

Syntax

Use open(filename, 'rb') to open a file in binary read mode. The read() method reads the file content as bytes. Always close the file after reading or use with to handle it automatically.

python
with open('file.bin', 'rb') as file:
    data = file.read()
💻

Example

This example opens a binary file named example.bin, reads its content, and prints the bytes read.

python
with open('example.bin', 'rb') as file:
    binary_data = file.read()
print(binary_data)
Output
b'\x00\x01\x02\x03\x04\x05'
⚠️

Common Pitfalls

  • Opening a binary file without 'rb' mode can cause errors or data corruption.
  • Not closing the file can lead to resource leaks; use with to avoid this.
  • Trying to print binary data directly may show unreadable characters; handle bytes carefully.
python
file = open('example.bin', 'r')  # Wrong: text mode
binary_data = file.read()
file.close()

# Correct way:
with open('example.bin', 'rb') as file:
    binary_data = file.read()
📊

Quick Reference

Remember these key points when reading binary files in Python:

  • Use 'rb' mode to open files.
  • Use with statement to manage file closing.
  • Read data as bytes using read().
  • Handle bytes carefully; convert if needed.

Key Takeaways

Always open binary files with 'rb' mode to read bytes correctly.
Use the 'with' statement to ensure files close automatically.
Read binary data using the read() method to get bytes.
Avoid printing raw binary data directly without processing.
Handle file operations carefully to prevent resource leaks.