reading a binary file in python code example

Example 1: read binary file python

file = open("sample.bin", "rb")
binary_data = file. read()

Example 2: reading binary file

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != b"":
        # Do stuff with byte.
        byte = f.read(1)

Example 3: file handling in python append byte

file = open('myfile.dat', 'wb')
file.write('This is a sample')
file.close()

file = open('myfile.dat', 'ab')
file.seek(5)
file.write(' text')
file.close()

file = open('myfile.dat', 'rb')
print file.read()  # -> This is a sample text