无法从Python中的二进制文件读取正确的值

发布于 2025-01-22 08:59:13 字数 769 浏览 3 评论 0原文

我创建并写入双(数据类型)值为二进制文件。该文件不包含任何标题。它只是使用QT中的QDataStream写入文件中的原始数据。我正在尝试读取Python(版本3.6.9)脚本中的值,但是,Python脚本中读取的数据不是corect。当在C ++中读取时,同一文件给出正确的数据值。我的python代码是:

with open("cont_points.dat", mode='rb') as f:
    controlP=np.fromfile(f,dtype=np.double)
print(controlP)

最后一个打印语句给出以下结果,我认为这是所有零:

[2.11855e-320 1.04347e-320 0.00000e+000 3.03865e-319 2.11855e-320
 2.05531e-320 0.00000e+000 3.03865e-319 1.61263e-320 1.04347e-320
 ... ... ...
 2.05531e-320 0.00000e+000 3.03865e-319 2.05531e-320 1.04347e-320
 0.00000e+000 3.03865e-319 2.05531e-320 2.05531e-320 0.00000e+000
 3.03865e-319]

文件中的数据为[-4、3、0、1,-4、4、4、0、1、1,-3.5、3 ,0,1,.... or]。总共有136个值我想阅读。当我在C ++中读取相同文件时,我会得到正确的结果,我认为问题在我的Python代码中。谁能告诉我在这里做错什么?

I created and wrote double (data type) values into a binary file. The file does not contain any headers. It is just raw data written into the file using QDataStream in Qt. I am trying to read the values in a python (version 3.6.9) script, however, the data that is read in the python script is not corect. The same file when read in c++ gives the correct data values. My python code is :

with open("cont_points.dat", mode='rb') as f:
    controlP=np.fromfile(f,dtype=np.double)
print(controlP)

The last print statement gives the following result, which i assume are all zeros:

[2.11855e-320 1.04347e-320 0.00000e+000 3.03865e-319 2.11855e-320
 2.05531e-320 0.00000e+000 3.03865e-319 1.61263e-320 1.04347e-320
 ... ... ...
 2.05531e-320 0.00000e+000 3.03865e-319 2.05531e-320 1.04347e-320
 0.00000e+000 3.03865e-319 2.05531e-320 2.05531e-320 0.00000e+000
 3.03865e-319]

the data in the file is [-4, 3, 0, 1, -4, 4, 0, 1, -3.5, 3, 0, 1,.... so on]. In total there are 136 values that i want to read. As i get the correct result when i read the same file in c++, I think the problem is in my python code. Can anyone please tell what am I doing wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海螺姑娘 2025-01-29 08:59:13

问题是文件中数据的端性。 QDATASTREAM默认使用Big Endian字节顺序。在您的系统上,Numpy使用了Little Endian。您可以使用dtype ='> f8'读取文件。

这将导致具有非本地字节顺序的数组(controlp.dtype.isnative将为false)。根据接下来发生的情况,您可能想在其上调用.byteswap(),以获得更好的性能。另请参见 numpy文档中的此页面。

The problem is the endianness of the data in the file. QDataStream by default uses big endian byte order. On your system numpy uses little endian. You can read the file using dtype='>f8'.

This will result in an array with non-native byte order (controlP.dtype.isnative will be False). Depending on what happens next you might want to call .byteswap() on it first for better performance. See also this page in the numpy docs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文