Exam-style question
Try this first
Write Python code that writes the three byte values 65, 66 and 67 to a binary file called letters.bin, then reads the file and displays the bytes that were read. The file must be closed safely after each operation.
Model answer
What a good answer should say
- with open("letters.bin", "wb") as file: file.write(bytes([65, 66, 67])) with open("letters.bin", "rb") as file: data = file.read() print(data)
Explanation
Why this works
The file is opened with wb for binary writing. bytes([65, 66, 67]) creates a bytes object containing the three specified values, which can be written to the file.
It is then reopened with rb for binary reading, and read() returns the stored bytes. Separate with statements safely close the file after writing and reading.
Common mistake
No common mistake is linked to this question yet.
