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?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Nourless
  • 729
  • 1
  • 5
  • 18
  • Can you give more details of what you want to do? – lhoupert Jul 10 '20 at 16:34
  • @lhoupert I updated the question, hope it's clear now – Nourless Jul 10 '20 at 16:41
  • Have you check these posts [here](https://stackoverflow.com/questions/43048921/how-to-use-function-like-matlab-fread-in-python) and [here](https://stackoverflow.com/questions/2146031/what-is-the-equivalent-of-fread-from-matlab-in-python)? – lhoupert Jul 10 '20 at 16:46
  • Does this answer your question? [What is the equivalent of 'fread' from Matlab in Python?](https://stackoverflow.com/questions/2146031/what-is-the-equivalent-of-fread-from-matlab-in-python) – lhoupert Jul 10 '20 at 16:47
  • @llhoupert No, as I said it is all examples without implementing of `skip` parameter. It's crucial for me – Nourless Jul 10 '20 at 16:52

1 Answers1

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.

mtrw
  • 34,200
  • 7
  • 63
  • 71
  • it raises a error `iterative unpacking requires a buffer of a multiple of 6 bytes` – Nourless Jul 11 '20 at 08:10
  • @Nourless - you need to create the file like in the MATLAB docs. `fwrite(fileID,[1:9],'uint16');` creates a file of exactly 18 bytes. – mtrw Jul 11 '20 at 11:12