JPV - 2 months ago 13

Python Question

I would like to write the equivalence of this matlab code to python when reading binary file

`fid=fopen('File', 'rb')`

fread(fid, 17, 'int8', 'l');

[twf, points] = fread(fid, 'int16', 'l');

twf = fread(fid, 'int16', 'l');

fclose(fid)

Thanks

Answer

Your code is incorrect in two places:

`fread`

returns the number of characters (bytes) read, not the number of data points read. Since you read`'int16'`

,`points`

is twice the number of data points in your case.- The last
`fread`

is not necessary, since`[twf, points] = fread(fid, 'int16', 'l');`

already reads the whole remaining file. Actually you are overwriting your read data with nothing.

Anyway, here is the Python/numpy code:

```
from numpy import fromfile
with open('File', 'rb') as fid:
fromfile(fid, '<i1', 17) # do we need to specify LE here?
twf = fromfile(fid, '<i2')
points = twf.size
```

Source (Stackoverflow)