Эффективный перевод на python из matlab fread

Мне нужно перевести Matlab fread на python, в частности, разрешить чтение в двумерный массив и пропустить данные при чтении. Я придумал следующее, но я думаю, что могут быть более эффективные и «питоновские» способы сделать это (я ни в коем случае не программист). Любое предложение? Обратите внимание, что я не могу прочитать весь файл, а затем выполнить подвыборку массива, поскольку файлы для чтения слишком велики.

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')

person user2061949    schedule 18.02.2013    source источник
comment
Вы могли бы просто обновить исходный вопрос, указав дополнительную информацию, а не удалять его.   -  person Dhara    schedule 18.02.2013


Ответы (1)


Это более или менее то, что у вас есть, может быть, немного чище.

def fromfileskip(fid,shape,counts,skip,dtype):
  """
  fid    : file object,    Should be open binary file.
  shape  : tuple of ints,  This is the desired shape of each data block.
           For a 2d array with xdim,ydim = 3000,2000 and xdim = fastest 
           dimension, then shape = (2000,3000).
  counts : int, Number of times to read a data block.
  skip   : int, Number of bytes to skip between reads.
  dtype  : np.dtype object, Type of each binary element.
  """
  data = np.zeros((counts,)  + shape)
  for c in xrange(counts):
    block = np.fromfile(fid,dtype=np.float32,count=np.product(shape))
    data[c] = block.reshape(shape)
    fid.seek( fid.tell() + skip)

  return data
person dermen    schedule 02.04.2013