Python Read Binary File
This day I have a problem to create Python read binary file. I have a binary file and want to create ptyhon to read binary file. Reading binary file with python is very simple. We can use ‘open’ function and adding parameter ‘b’ if we wanto to python read binary file. This is a simple code how to read binary file with python :
filename = '/data/temp/tmpfile.sgy' # input file name fid = open(filename, "rb") # read input file with option read as binary head1 = fid.read(3200) # read 3200 byte from input file fid.close() # close file
From this example, I try to create python read binary file with size of data is 3200 byte. If we wanto to display output from this data, we can use command :
Output from this command is character from 3200 byte from our input file. We can display our data in integer representing the Unicode code point of the character use command ord. For example, ord(‘a’) returns the integer 97. So, if we want to display our data in integer, we can loop our data and convert that with ord command. This is a simple code how to do that :
for i in range(3200) print ord(head1[i])
This is my simple posting about to create python read binary file code. In my next post, I will create a tutorial how Python write binary file.