Python - File Binary File

Introduction

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

Demo

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  w  w w  .j  ava2  s .  co 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

Result