206k views
0 votes
Assume the file contains a sequence of binary data. Write a program that:

Displays the first 5 bytes stored in the file, each on a separate line.

User Teerasej
by
8.2k points

1 Answer

3 votes

Final answer:

To display the first 5 bytes of a binary file in Python, open the file in binary read mode and read one byte at a time in a loop, then print each byte until you have printed five.

Step-by-step explanation:

Displaying Binary Data from a File in Python

To display the first 5 bytes of binary data from a file in Python, you can use the following script:

with open('binaryfile.bin', 'rb') as file: # Open the file in binary read mode
for _ in range(5): # Loop to read the first 5 bytes
byte = file.read(1) # Read a single byte
if not byte:
break
print(byte) # Display the byte

Make sure to replace 'binaryfile.bin' with the actual filename of your binary file. This script opens the file in binary read mode, reads each byte one at a time, and prints it until it has printed 5 bytes or reached the end of the file.

User Bob De Graaf
by
7.3k points