简体   繁体   English

TypeError:Python文件中无法理解的数据类型

[英]TypeError: data type not understood in Python fromfile

I am trying to read a binary file using following command: 我正在尝试使用以下命令读取二进制文件:

import numpy as np
fid = open(filename, 'rb')
ax = np.fromfile(fid, dtype=np.int32, count=1)

This command is working fine, However 这个命令运行正常,但是

ay = np.fromfile(fid, dtype=np.char, count=16)

gives an TypeError: data type not understood. 给出一个TypeError:数据类型不被理解。 Any idea how can i read it as character type? 任何想法我怎么能把它读作字符类型?

Your desired data type is non-existent, np.char actually is a module . 您所需的数据类型不存在, np.char实际上是一个模块

Take a look at the numpy datatypes , you could cover your byte representation using np.byte , which is a np.int8 . 看看numpy数据类型 ,您可以使用np.byte覆盖您的字节表示,这是一个np.int8

You should use 你应该用

ay = np.fromfile(fid, dtype=np.byte, count=16)

instead of 代替

ay = np.fromfile(fid, dtype=np.char, count=16)

because numpy doesn't contain scalar type char . 因为numpy不包含标量类型的char More about numpy data types you could see here . 有关numpy数据类型的更多信息,请参阅此处 numpy.byte type corresponding to C char type. numpy.byte类型对应于C char类型。
If you want convert array of 16 binary digits to one int you can use following code: 如果要将16位二进制数字转换为一个int ,可以使用以下代码:

aybin = np.fromfile(fid, dtype=np.char, count=16)
ay = int(("".join(str(d) for d in aybin)), 2)

So, after I saw your communication via comments, I update my answer as follows: 所以,在我通过评论看到您的沟通后,我更新了我的答案如下:

In your case you should use: 在你的情况下你应该使用:

ay = np.fromfile(fid, dtype=np.byte, count=16)

However I leave the parts of my previous answer here to consider to use in other particular case. 但是,我在此处留下我之前回答的部分内容,以考虑在其他特定情况下使用。

Try numpy.loadtxt() . 试试numpy.loadtxt()

More flexible way of loading data from a text file. 从文本文件加载数据的更灵活方式。

But if you even use numpy.fromfile() , then you have to use the arg sep , because empty (“”) separator means the file should be treated as binary . 但是如果你甚至使用numpy.fromfile() ,那么你必须使用arg sep ,因为空(“”)分隔符意味着文件应该被视为二进制

As you can read here , in numpy manual: 你可以在这里看到 ,在numpy手册中:

sep : str sep:str

Separator between items if file is a text file. 如果文件是文本文件,则项目之间的分隔符。 Empty (“”) separator means the file should be treated as binary. 空(“”)分隔符表示该文件应被视为二进制文件。 Spaces (” ”) in the separator match zero or more whitespace characters. 分隔符中的空格(“”)匹配零个或多个空白字符。 A separator consisting only of spaces must match at least one whitespace. 仅由空格组成的分隔符必须至少匹配一个空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM