Reading and writing binary files
Opens a file in binary mode so read() returns raw bytes, not text. Use 'wb' to write bytes. Binary data is type bytes, not str, and read(n) reads n bytes.
Understanding Reading and writing binary files in QCE Digital Solutions Unit 4
What it does: read(n) on a binary file returns up to n bytes as a bytes object, so read(4) gets 4 bytes. The b before the quotes makes a bytes value, which is what a file opened with 'wb' accepts. 'wb' means write binary. 'w' writes text (str), not bytes. Images are binary data. Reading them in text mode tries to decode them as characters and can fail or corrupt the data. Speed is not the reason.
Common mistakes: read is a method, so the number of bytes goes in round brackets: f.read(4). Square brackets are for indexing, not for calling a method. A file opened with 'wb' only accepts bytes. str(data) turns it into text, which raises a TypeError. It should be f.write(data).
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 334–401) and word search (Modules 127–401).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
open('data.bin', 'rb')Fill in the Blanks
Spot the Error
Student with a class code? Join your class →