python - Interpreting binary files as ASCII -
i have binary file (which i've created in c) , have inside file. obviously, won't able "see" useful it's in binary. know contains number of rows numbers in double precision. looking script read values , print them can verify if in right range. in other words, doing head or tail in linux on text file. there way of doing it? right i've got in python, not want:
chunksize = 8192 file = open('eigenvalues.bin', 'rb') data = list(file.read()) print data
use array module read homogenous binary-representation numbers:
from array import array data = array('d') chunksize = 8192 rowcount = chunksize / data.itemsize # number of doubles find in chunksize bytes open('eigenvalues.bin', 'rb') eg: data.fromfile(eg, rowcount) the array.array type otherwise behaves list, type of values can hold constricted (in case float).
depending on input data, may need add data.byteswap() call after reading switch between little , big-endian. use sys.byteorder see byteorder used read data. if data written on platform using little-endianess, swap if platform uses other form, , vice-versa:
import sys if sys.byteorder == 'big': # data written in little-endian form, swap bytes match data.byteswap()
Comments
Post a Comment