Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

How to Read a Binary File into a Byte Array in Python

Read a Python binary file with "rb" to get bytes; convert to bytearray for edits or process large files in chunks to limit memory use.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Open the file in binary mode and call read() to load its contents as Python bytes:

with open("data.bin", "rb") as file:
    data = file.read()

Use bytearray(data) if you need to change individual bytes. For a large file, read and process bounded chunks instead of loading the entire file into memory.

Read the entire file as bytes

Use "rb" for read-binary mode. The "b" tells Python not to decode the file into text, so read() returns a bytes object containing the raw contents. The with block closes the file when the block ends.

with open("data.bin", "rb") as file:
    data = file.read()

print(type(data))  # <class 'bytes'>

This is the straightforward choice when the whole file is small enough to keep in memory. Python’s built-in open() documentation describes binary file modes and their return type.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use pathlib for a concise whole-file read

If you do not need to keep an open file stream for additional operations, Path.read_bytes() reads and returns the file’s contents as bytes, opening and closing the file for the operation.

from pathlib import Path

data = Path("data.bin").read_bytes()

See the Path.read_bytes() documentation for the method details.

Convert to a mutable bytearray when needed

Python’s ordinary binary read returns immutable bytes. The built-in mutable type is bytearray; convert the data if you need to replace or edit byte values.

with open("data.bin", "rb") as file:
    data = file.read()

mutable_data = bytearray(data)
if mutable_data:
    mutable_data[0] = 0x41

The if check avoids indexing an empty file. A memoryview is another option when an API accepts buffer objects and you want to access binary data without making a copy. See the documentation for bytes, bytearray, and memoryview.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read a large file in chunks

A whole-file read retains the entire file in memory. To keep memory use bounded, read a chunk, handle it, and then continue. This example processes each chunk without storing all of them:

with open("large.bin", "rb") as file:
    while chunk := file.read(64 * 1024):
        process(chunk)

Replace process(chunk) with the operation your program needs to perform. The loop ends when read() returns an empty byte string at end-of-file. If you collect every chunk in a list and later join them, you will still need memory for the complete file.

Fill and reuse a mutable buffer with readinto()

If you need to read into storage you have already allocated, readinto() accepts a writable bytes-like buffer, such as a bytearray, and returns how many bytes it read. A call may read fewer bytes than the buffer’s capacity, so process only the portion indicated by the returned count.

buffer = bytearray(64 * 1024)

with open("large.bin", "rb") as file:
    while count := file.readinto(buffer):
        process(memoryview(buffer)[:count])

This reuses the same buffer on each iteration. A downstream function that needs to retain the data beyond the next read should make its own copy. See Python’s I/O stream documentation for read(), readinto(), and in-memory binary streams such as io.BytesIO.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Binary mode versus text mode

Text mode, selected by "r", decodes file bytes into a Python string. Binary mode, selected by "rb", returns bytes without decoding. Use binary mode for arbitrary binary data, or when you deliberately need the underlying bytes of a text-formatted file. If you later want to interpret those bytes as text, decode them separately using the encoding you know the file uses.

As the Python tutorial puts it: “Binary mode data is read and written as bytes objects.” See the file-reading and writing tutorial.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.