Quick answer: Open a file with wb to overwrite it with bytes, ab to append, or use Path.write_bytes for a small complete payload. Encode text explicitly and use a context manager so the file is closed on both success and failure.

To write bytes to a file in Python, open the file in binary mode and pass a bytes object to write(). Binary mode matters because Python should store the exact byte values without trying to decode them as text or translate line endings.
Use this pattern for images, audio files, network packets, compressed data, cache files, and any value that is already represented as bytes. If you are starting with a string, encode it first. If you need to convert bytes back into text later, see the guide to Python bytes to string.
Binary writing is also different from serialization. Python will not automatically turn dictionaries, lists, or custom objects into a portable file format just because the file is opened with "wb". Convert the value to the exact bytes you want first, then write those bytes deliberately. That keeps the file predictable across operating systems.
Write Bytes With open() and wb
The most direct approach is open(path, "wb"). The w means write, and the b means binary. This mode creates the file if it does not exist and replaces the file if it already exists.
data = b"PythonPool binary example\n"
with open("output.bin", "wb") as file:
bytes_written = file.write(data)
print(bytes_written)
write() returns the number of bytes written. That return value is useful when debugging generated files or checking that a program wrote the expected payload size. If the file is part of a pipeline, log the count along with the destination path.
Write Bytes With pathlib
Path.write_bytes() is a compact alternative when you already use pathlib. It opens the file, writes the bytes, closes the file, and returns the number of bytes written.
from pathlib import Path
path = Path("output.bin")
path.parent.mkdir(parents=True, exist_ok=True)
count = path.write_bytes(b"Saved with pathlib\n")
print(count)
Create the parent directory first when writing into a nested folder. The related article on Python touch file covers parent directory creation and file preparation patterns. write_bytes() is best for whole-file writes; use a file object when writing many chunks.

Append Bytes to an Existing File
Use append-binary mode when new bytes should be added to the end instead of replacing the file. The mode is "ab". This is useful for simple logs, packet dumps, or streaming chunks into one output file.
chunks = [b"chunk-1\n", b"chunk-2\n", b"chunk-3\n"]
with open("chunks.bin", "ab") as file:
for chunk in chunks:
file.write(chunk)
print("chunks appended")
Append mode does not add separators automatically. Include newlines, length headers, or another delimiter yourself when the file format needs boundaries between chunks.
Encode Text Before Writing Bytes
Strings are text, not bytes. If the source value is a Python string, call encode() before writing it to a binary file. UTF-8 is the best default for most modern text data.
message = "cafe prices: 5 euros"
encoded = message.encode("utf-8")
with open("message.bin", "wb") as file:
file.write(encoded)
print(encoded)
Use the same encoding when reading the bytes back as text. The official Python documentation lists the standard encodings available when your file must match another system.

Write Hex Bytes
Hexadecimal strings are common in examples, protocols, and tests. Convert a hex string to bytes with bytes.fromhex(), then write the result in binary mode.
hex_value = "89504e470d0a1a0a"
png_header = bytes.fromhex(hex_value)
with open("header.bin", "wb") as file:
file.write(png_header)
print(png_header)
This is helpful when constructing fixtures or checking file signatures. Keep the hex string even-length and avoid adding spaces unless you intend Python to ignore them.
Read Back Bytes to Verify the File
After writing a file, read a small sample or compare the whole payload when correctness matters. Binary read mode is "rb". For large files, compare sizes or hashes instead of loading everything into memory.
expected = b"PythonPool binary example\n"
with open("output.bin", "wb") as file:
file.write(expected)
with open("output.bin", "rb") as file:
actual = file.read()
print(actual == expected)
Before reading a user-supplied path, it is often worth checking whether the file exists. The guide on checking if a file exists in Python covers those checks. For text workflows, use read file line by line instead of binary reads.

Common Mistakes
The most common mistake is opening a file with "w" and then passing bytes. Text mode expects strings, while binary mode expects bytes-like objects. Another mistake is forgetting that "wb" overwrites an existing file. Use "ab" only when appending is the intended behavior.
Use open(..., "wb") for explicit file control, Path.write_bytes() for concise whole-file writes, and open(..., "ab") for appending byte chunks. If a temporary binary file should be removed after processing, review how to delete a file in Python. Keep binary file formats documented so future code can read the bytes in the same order.
References
- Python documentation for open()
- Python documentation for Path.write_bytes()
- Python documentation for bytes
- Python standard encodings
Overwrite Or Append Bytes
Binary mode does not decode or encode data for you. wb creates a new file or truncates an existing one, while ab preserves the existing bytes and writes at the end. Choose the mode from the data contract, not from convenience.
from pathlib import Path
Path("output.bin").write_bytes(b"header\x00body")
with open("output.bin", "ab") as handle:
handle.write(b"\nfooter")

Keep Text And Bytes Boundaries Clear
If the source is text, choose an encoding and convert it to bytes. If the destination is a text file, open it in text mode instead. Mixing str and bytes in one write operation raises a TypeError and can hide an encoding decision that should be documented.
text = "café"
encoded = text.encode("utf-8")
with open("message.bin", "wb") as handle:
handle.write(encoded)
print(Path("message.bin").read_bytes().decode("utf-8"))
Stream Large Data And Verify
For large data, iterate over the source in chunks rather than building one enormous bytes object. A context manager closes the output even if a write fails. Read back a digest or a bounded prefix when a pipeline needs a lightweight correctness check.
import hashlib
digest = hashlib.sha256()
with open("source.bin", "rb") as source, open("copy.bin", "wb") as target:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
target.write(chunk)
digest.update(chunk)
print(digest.hexdigest())
Python’s open() documentation defines binary modes, and Path.write_bytes() provides a concise complete-write method.
For related file workflows, compare bytes conversion, copying files, and line-by-line reads before choosing a binary I/O boundary.
Frequently Asked Questions
How do I write bytes to a file in Python?
Open the path with mode ‘wb’ and call write() with a bytes-like value, or use Path.write_bytes() for a complete byte string.
What is the difference between wb and ab?
wb creates or truncates the file before writing, while ab preserves existing bytes and appends at the end.
Can I write text with a binary file handle?
No. Encode the text explicitly, such as text.encode(‘utf-8’), or open the file in text mode with the desired encoding.
How do I write a large binary file safely?
Stream the source in chunks and write each chunk to a file opened with a context manager so the handle closes even when an error occurs.
#By: Ishraga Mustafa Awad Allam. On:21-11- 2021.
import struct
fil = input(“Enter your file name, please: “)
file = open(fil, “wb”)
m = int(input(“Enter list size: “))
c = list(range(m))
for x in range(0, m):
b = float(input(” Enter list item: “))
c[x] = b
print(c)
b = struct.pack(‘<‘+’f’*len(c), *c)
with open(fil, “wb”) as file:
file.write(b)
file.close()
file = open(fil, “rb”)
byte = file. read(4)
i = 0
y = list(range(m))
while byte: #byte=false at end of file.
x = struct.unpack(‘<f’, byte)
print(‘%8.3f’%x)
y[i] = x
byte = file. read(4)
i = i + 1
print(y)
file.close()
That’s one unique way to do it!