How to Write Bytes to a File in Python

To write bytes to a file in Python, open it in binary write mode with open(path, "wb") and call f.write(data), where data is a bytes or bytearray object. For a one-liner, Path(path).write_bytes(data) does the same:

with open("invoice.bin", "wb") as f:
    f.write(data)

Binary mode works the same on every OS, but I ran these on Windows with Python 3.12.5, where text-mode newline translation would otherwise change your bytes.

You’ll see wb mode and what write() returns, the str-vs-bytes TypeError, pathlib, appending, building bytes from numbers, fixed-size records with struct, and copying a big file in chunks.

Write bytes to a file with open() in wb mode

"wb" creates the file or empties an existing one. write() returns how many bytes it wrote, which is handy for logging:

data = "Invoice #1042 - $129.99 - Austin, TX\n".encode("utf-8")

with open("invoice.bin", "wb") as f:
    written = f.write(data)          # returns the number of bytes written
print("wrote", written, "bytes")

with open("invoice.bin", "rb") as f:
    raw = f.read()
print(raw)
print(raw.hex(" ", 4))

Output:

wrote 37 bytes
b'Invoice #1042 - $129.99 - Austin, TX\n'
49 6e766f69 63652023 31303432 202d2024 3132392e 3939202d 20417573 74696e2c 2054580a
Command Prompt output of Python writing encoded bytes to a file in wb mode, reading them back and printing them as hex
write() reports the byte count, and reading the file back shows the same bytes as a bytes literal and as hex.

encode("utf-8") turns text into bytes. The other direction, and the encoding choices, are in converting a string to bytes in Python.

Why do I get “a bytes-like object is required, not ‘str'”?

Binary files only accept bytes, and text files only accept strings. Mixing them raises a TypeError either way:

with open("notes.bin", "wb") as f:
    try:
        f.write("Café order")
    except TypeError as err:
        print("TypeError:", err)

with open("notes.txt", "w", encoding="utf-8") as f:
    try:
        f.write(b"Cafe order")
    except TypeError as err:
        print("TypeError:", err)

Output:

TypeError: a bytes-like object is required, not 'str'
TypeError: write() argument must be str, not bytes
Command Prompt output of Python TypeError when writing a str to a binary file and bytes to a text file
Writing text to a wb file needs a bytes-like object, and writing bytes to a w file needs a str.

Encode text before writing it in binary mode, or decode bytes to write them as text. There’s a related error in the cannot concat str to bytes error.

Write bytes with pathlib, append mode and bytes()

Path.write_bytes() opens, writes and closes in one call. Use "ab" to add to the end of a file, and bytes([...]) to build data from numbers:

from pathlib import Path

header = bytes([0x89, 0x50, 0x4E, 0x47])            # first bytes of a PNG file
Path("header.bin").write_bytes(header)
print(Path("header.bin").read_bytes(), Path("header.bin").stat().st_size, "bytes")

with open("header.bin", "ab") as f:                 # append mode
    f.write(bytearray(b"\x0d\x0a"))
print(Path("header.bin").read_bytes())

try:
    bytes([72, 105, 256])
except ValueError as err:
    print("ValueError:", err)

Output:

b'\x89PNG' 4 bytes
b'\x89PNG\r\n'
ValueError: bytes must be in range(0, 256)

Each number must be 0 to 255, so 256 raises a ValueError. For a mutable buffer you can change before writing, see the Python bytearray() function.

Write fixed-size binary records with struct

When another program reads your file, you need an exact layout. struct packs numbers and fixed-width text into bytes:

import struct
from datetime import date

RECORD = struct.Struct("<I10sd")                    # uint32 id, 10-byte state+date, float64 amount
sales = [(1001, "TX20261006", 129.99), (1002, "CA20261006", 54.50), (1003, "NY20261007", 230.25)]

with open("sales.dat", "wb") as f:
    for sale_id, key, amount in sales:
        f.write(RECORD.pack(sale_id, key.encode("ascii"), amount))

print("record size:", RECORD.size, "bytes; file size:", RECORD.size * len(sales))
with open("sales.dat", "rb") as f:
    for sale_id, key, amount in RECORD.iter_unpack(f.read()):
        key = key.decode("ascii")
        print(sale_id, key[:2], date.fromisoformat(f"{key[2:6]}-{key[6:8]}-{key[8:]}"), f"${amount:.2f}")

Output:

record size: 22 bytes; file size: 66
1001 TX 2026-10-06 $129.99
1002 CA 2026-10-06 $54.50
1003 NY 2026-10-07 $230.25
Command Prompt output of Python struct packing sales records into a binary file and unpacking them again
Each sales record takes 22 bytes, and unpacking the file returns the IDs, states, dates and dollar amounts.

< means little-endian with no padding, so every record is exactly the same size. Converting numbers on their own is shown in converting an int to bytes in Python.

Write a large binary file in chunks

Reading a whole video or backup into memory just to write it again wastes RAM. Copy it in fixed-size chunks and check the result with a hash:

import hashlib
import os

with open("backup.zip", "wb") as f:
    f.write(os.urandom(25 * 1024 * 1024))           # 25 MB of test data

CHUNK = 1024 * 1024
copied = 0
with open("backup.zip", "rb") as src, open("backup_copy.zip", "wb") as dst:
    while chunk := src.read(CHUNK):
        copied += dst.write(chunk)

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(CHUNK), b""):
            h.update(block)
    return h.hexdigest()[:16]

print(f"copied {copied / 1_048_576:.0f} MB in {CHUNK // 1024} KB chunks")
print("same content:", sha256("backup.zip") == sha256("backup_copy.zip"))

Output:

copied 25 MB in 1024 KB chunks
same content: True
Command Prompt output of Python copying a 25 MB binary file in 1 MB chunks and confirming matching SHA-256 hashes
The 25 MB file is copied in 1024 KB chunks, and the hashes confirm the copy is identical.

For plain copies, shutil.copyfile() does this for you. To read the data back in pieces, see reading a binary file in Python.

File modes for writing bytes

ModeDoesExisting file
"wb"Write bytesEmptied first
"ab"Append bytesKept, writes at the end
"xb"Create and write bytesRaises FileExistsError
"r+b"Read and overwrite in placeKept
Path.write_bytes()Same as "wb"Replaced

More file-writing guides you might want:

Frequently asked questions

How do I write bytes to a file in Python?

Open the file with open(path, "wb") and call f.write(data) with a bytes object.

What’s the difference between “w” and “wb”?

“w” writes text and translates newlines; “wb” writes raw bytes unchanged.

How do I append bytes to an existing file?

Open it with mode "ab" and write the new bytes.

How do I write a string as bytes?

Encode it first: f.write(text.encode("utf-8")).

How do I write a very large binary file without using too much memory?

Write it in chunks, for example 1 MB at a time in a loop.

Where is open() documented?

See open() in the Python docs.