logo

Question detail

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.

Try the question, check the answer, then read the explanation to understand the curriculum point.

At a glance

Question

Type

practice

Style

Topic

Data structures and abstract data types

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.

Related flashcards

No flashcards are published for this page yet.

Related practice questions

No questions are published for this page yet.