1

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?

5
  • Can you give more details of what you want to do? Commented Jul 10, 2020 at 16:34
  • @lhoupert I updated the question, hope it's clear now Commented Jul 10, 2020 at 16:41
  • Have you check these posts here and here? Commented Jul 10, 2020 at 16:46
  • Does this answer your question? What is the equivalent of 'fread' from Matlab in Python? Commented Jul 10, 2020 at 16:47
  • @llhoupert No, as I said it is all examples without implementing of skip parameter. It's crucial for me Commented Jul 10, 2020 at 16:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

it raises a error iterative unpacking requires a buffer of a multiple of 6 bytes
@Nourless - you need to create the file like in the MATLAB docs. fwrite(fileID,[1:9],'uint16'); creates a file of exactly 18 bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.