Reading a Binary File
First we need to open the file in read binary mode. Make sure the file exists first.
my_file = open(“data.dat”, “rb”)
To read the data, we can use the read() method. The read() method is used to read a specified number of bytes from a file or the entire content if no size is specified. It returns a byte object in binary mode containing the data.
content = my_file.read()
print(content)
Using the read() method you can also specify the number of bytes to read. The following example will read the first 4 bytes of the file.
binary_data = file.read(4)
You can also use the readline() method. The readline() method is used to read a single line from a file. It returns a byte object in binary mode representing the line.
line = my_file.readline() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access