Python - File Binary File


In Python 3.X, and assuming an existing binary file:


myfile = open('data.bin', 'wb')        # Open for text output: create/empty 
myfile.write(b'hello text file\n')       # Write a line of text: string 
myfile.write(b'goodbye text file\n') 
myfile.close()                          # Flush output buffers to disk 
# from  ww w  . j  a  va 2 s  .c  o m

data = open('data.bin', 'rb').read()# Open binary file: rb=read binary 
print( data )                       # bytes string holds binary data 
print( data[4:8] )                  # Act like strings 
print( data[4:8][0] )               # But really are small 8-bit integers 
print( bin(data[4:8][0]) )          # Python 3.X/2.6+ bin() function