I am trying to convert Matlab code to Python for binary files. Forgive me l am new to this language.
Matlab:
fileID = fopen('file_name.bin','r');
DC = fread(fileID,'single','b');
Python:
import numpy as np
with open('Duty_Cycle.bin','rb') as fid:
data_array = np.fromfile(fid, np.float32, dtype = '>u4')
print(data_array)
Result:
TypeError: argument for fromfile() given by name ('dtype') and position (2)
How can I fix this error?
The signature for fromfile
is
fromfile(file, dtype=float, count=-1, sep='', offset=0)
By specifying both the second positional argument np.float32
and the keyword argument dtype='>u4'
, you gave the same parameter twice, and thus the error. The documentation isn't terribly clear, but you can just use the string specification to specify both the type and endianness.
data_array = np.fromfile(fid, dtype='>u4')