How to read part of binary file with numpy?

后端 未结 4 782
春和景丽
春和景丽 2020-12-18 21:24

I\'m converting a matlab script to numpy, but have some problems with reading data from a binary file. Is there an equivelent to fseek when using fromfile

4条回答
  •  一生所求
    2020-12-18 21:55

    This is what I do when I have to read arbitrary in an heterogeneous binary file.
    Numpy allows to interpret a bit pattern in arbitray way by changing the dtype of the array. The Matlab code in the question reads a char and two uint.

    Read this paper (easy reading on user level, not for scientists) on what one can achieve with changing the dtype, stride, dimensionality of an array.

    import numpy as np
    
    data = np.arange(10, dtype=np.int)
    data.tofile('f')
    
    x = np.fromfile('f', dtype='u1')
    print x.size
    # 40
    
    second = x[8]
    print 'second', second
    # second 2
    
    total_cycles = x[8:12]
    print 'total_cycles', total_cycles
    total_cycles.dtype = np.dtype('u4')
    print 'total_cycles', total_cycles
    # total_cycles [2 0 0 0]       !endianness
    # total_cycles [2]
    
    start_cycle = x[12:16]
    start_cycle.dtype = np.dtype('u4')
    print 'start_cycle', start_cycle
    # start_cycle [3]
    
    x.dtype = np.dtype('u4')
    print 'x', x
    # x [0 1 2 3 4 5 6 7 8 9]
    
    x[3] = 423 
    print 'start_cycle', start_cycle
    # start_cycle [423]
    

提交回复
热议问题