Nourless
Nourless

Reputation: 854

What is equivalent of MATLAB's fread with skip parameter in Python?

I wonder how can I implement MATLAB

fread(fileID,sizeA,precision,skip)

in Python (documentation). There are many advices how to deal with it in case of

fread(fileID,sizeA,precision)

but I need the skip parameter. So I want to obtain some

def fread(fileID,sizeA,precision,skip):
    # some code which do the same thing as matlab fread(fileID,sizeA,precision,skip)
    pass

How can it be implemented without symbol-wise reading?

Upvotes: 1

Views: 262

Answers (1)

mtrw
mtrw

Reputation: 35088

You can use Python's struct module to parse complex binary structures, including pad bytes. For instance, copying the Matlab doc, if you want to read a file of 2 short ints followed by 2 pad bytes:

import struct
fmt = "=hhxx" #native endianness and no alignment (=), two shorts (h), two pad bytes (x)
data = [x for x in struct.iter_unpack(fmt, open("nine.bin", "rb").read())]
## [(1, 2), (4, 5), (7, 8)]

Note that the output of struct.iter_unpack, and the other unpack methods, is a tuple.

Upvotes: 1

Related Questions