TypeError: data type not understood in Python fromfile
I am trying to read a binary file using the following command:
import numpy as np fid = open(filename, 'rb') ax = np.fromfile(fid, dtype=np.int32, count=1)
This command works fine, however
ay = np.fromfile(fid, dtype=np.char, count=16)
gives type TypeError: data type is not clear. Any idea how I can read it as a character type?
source to share
The desired data type does not exist, np.char
in fact a module .
Take a look at the numpy
datatypes , you can cover your byte representation using np.byte
which is np.int8
.
source to share
You must use
ay = np.fromfile(fid, dtype=np.byte, count=16)
instead
ay = np.fromfile(fid, dtype=np.char, count=16)
because it numpy
does not contain a scalar type char
. numpy
You can see more details about data types here . numpy.byte
corresponding to the type C char
.
If you want to convert an array of 16 binary digits to one int
, you can use the following code:
aybin = np.fromfile(fid, dtype=np.char, count=16)
ay = int(("".join(str(d) for d in aybin)), 2)
source to share
So, after I saw your post via the comments, I update my answer as follows:
In your case, you should use:
ay = np.fromfile(fid, dtype=np.byte, count=16)
However, I'm leaving parts of my previous answer here to consider using it in another special case.
Try it numpy.loadtxt()
.
A more flexible way to load data from a text file.
But if you even use numpy.fromfile()
, you need to use arg sep
, because an empty ("") delimiter means the file should be treated as binary .
As you can read here in the numpy manual:
sep: str
Separator between items if the file is a text file. A blank (") delimiter means the file should be treated as binary. Spaces (" ") in the delimiter match zero or more whitespace characters. A whitespace-only delimiter must match at least one space.
source to share