Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 07

Binary Files — Read and Write Bytes with Mode b

Open Python files in binary mode with b, copy bytes with read and write, and keep images and other media out of text mode.

Intermediate25 min
Binary files hero Module 16 Lesson 7 mode b byte copy

Text mode decodes characters. Binary mode keeps the raw bytes. Images, audio, video, and pickle files must use b.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • How binary files differ from text files
  • The modes "rb", "wb", and "ab"
  • How to copy a byte record from one file to another
  • Why this lesson uses a bytes value instead of a downloaded image

The idea

Copy a binary record without decoding it

A binary file holds bytes. Photos (.png, .jpg), audio, and video are binary. A PDF that embeds images is treated as binary too. Opening those in text mode can corrupt them because Python tries to decode bytes as characters.

Add b to the mode:

Mode Meaning
rb Read bytes. The file must exist.
wb Write bytes. Overwrites an existing file.
ab Append bytes.

handle.read() in binary mode returns a bytes object, not a str. handle.write() then expects bytes, not a regular string.

A copy is three steps: read every byte from the source, write those same bytes to the target, and let with close both pointers. This lesson copies a small bytes value named packet.bin. It is original practice data, not a photo from the web and not a file copied out of a notes folder.

Pickle files in the next lesson are also binary. They use "wb" and "rb".

Example

python
payload = bytes([65, 66, 67, 10, 49, 50, 51])
with open("packet.bin", "wb") as handle:
    handle.write(payload)

with open("packet.bin", "rb") as source, open("packet-copy.bin", "wb") as target:
    target.write(source.read())

with open("packet-copy.bin", "rb") as handle:
    print(handle.read())

The printed result looks like b'ABC\n123'. Those are the same bytes, not a new text encoding. The playground prints both the copy and source.closed after the with block.

Key takeaways

  • Binary files store bytes; text files store characters

  • Request binary mode with b

  • rb reads, wb overwrites, ab appends

  • Copy by reading bytes and writing those same bytes

  • Do not open images or pickle data in text mode

  • Previous: tell() and seek()

  • Next: Pickling and Unpickling

Loading playground…

Check your understanding

Binary files quiz

A binary file contains:

1 / 10