读一个二进制.dat文件作为一个数组 [英] Reading a binary .dat file as an array

查看:210
本文介绍了读一个二进制.dat文件作为一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个code,通过多次迭代去。在每次迭代中,code产生numpy的基于阵列。我追加基于numpy的阵列到现有的二进制.dat文件。我用下面的code生成数据:

I have a code that goes through several iterations. In each iteration, the code generates a numpy based array. I append the numpy based array to an existing binary .dat file. I use the following code to generate the data:

WholeData = numpy.concatenate((Location,Data),axis=0)  
# Location & Data are two numpy arrays
DataBinary = open('DataBinary.dat','ab')
WholeData.tofile(DataBinary)
DataBinary.close()

我想读取整个二进制文件到一个数组。我有以下困难:

I am trying to read the whole binary file into an array. I am having the following difficulties:


  1. 我尝试以下code:

  1. I tried the following code:

NewData = numpy.array('f')
File1 = open('DataBinary.dat','rb')
NewData.fromstring(File1.read())
File1.close()

错误状态:

回溯(最近通话最后一个):
   文件,1号线,在
  AttributeError的:numpy.ndarray'对象有没有属性'fromstring

Traceback (most recent call last): File "", line 1, in AttributeError: 'numpy.ndarray' object has no attribute 'fromstring'

我试图使用一个基于阵列的数组,然后读取文件放入数组。

  • I tried to use an array based array and then read the file into the array.

    from array import array
    File1 = open('DataBinary.dat','rb')
    NewData.fromstring(File1.read())
    File1.close()
    


  • 然而, NewData 是错误的,即它不一样的 WholeData 。我想,在保存数据为 numpy.array 和阅读为 array.array 可能不是一个好的选择。

    However, NewData is erroneous, i.e., it is not same as WholeData. I guess that saving the data as numpy.array and reading it as array.array might not be a good option.

    任何建议将AP preciated。

    Any suggestion will be appreciated.

    推荐答案

    我觉得numpy.fromfile是你想要的这里:

    I think that numpy.fromfile is what you want here:

    import numpy as np
    myarray = np.fromfile('BinaryData.dat',dtype=float)
    

    另外请注意,根据文档,这不是数据存储为关于precision和字节顺序信息丢失的最佳途径。换句话说,你需要确保传递到D型数据类型是与你最初写的文件兼容。

    Also note that according to the docs, this is not the best way to store data as "information on precision and endianness is lost". In other words, you need to make sure that the datatype passed to dtype is compatible with what you originally wrote to the file.

    这篇关于读一个二进制.dat文件作为一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆