I need to translate Matlab fread into python, in particular allowing for reading into a 2d array and skipping data while reading. I came up with the following, but I guess there may be more efficient and 'pythonic' ways to do it (I am by no means a programmer). Any suggestion? Note that I can't read the whole file and then subsample the array as the files to be read are too large.
def FromFileSkip(fid, count=1, skip=0, dtype=np.float32):
if np.ndim(count)==0:
if skip>=0:
data = np.zeros(count, dtype=dtype)
k = 0
while k<count:
data[k] = np.fromfile(fid, count=1, dtype=dtype)
fid.seek(skip, 1)
k +=1
return data
elif np.ndim(count)==1:
if skip>0:
data = np.zeros(count, dtype=dtype)
k = 0
while k<count[1]:
data[:,k] = np.fromfile(fid, count=count[0], dtype=dtype)
fid.seek(skip, 1)
k +=1
return data
else:
raise ValueError('File can be read only into 1d or 2d arrays')