Reading a binary .dat file as an array

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

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 entire binary file into an array. I have the following difficulties:

  • I tried the following code:

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

    Error Status:

    Traceback (last last call): File "", line 1, in AttributeError: object 'numpy.ndarray' does not have the attribute 'fromstring'

  • I tried using an array based array and then read the file in the array.

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

However, NewData is erroneous, i.e. he is not like WholeData . I think storing data as numpy.array and reading it as array.array may not be a very good option.

Any suggestion would be appreciated.

+7
source share
3 answers

I think numpy.fromfile is what you want here:

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

Also note that, according to the docs, this is not the best way to store data, because "the accuracy and byte order information is lost." In other words, you need to make sure that the data type passed to dtype is compatible with what you originally wrote to the file.

+23
source

To read a binary from file to list:

 list_int = [ord(i) for i in fd.read()] 
0
source

I'm just curious, but if you work in the laboratory of Jupiter, for example, he will not open this document or any other with .dat or .baseline for no reason. Not until you give him the full location of the document. So how can you really do this? Thanks!

0
source

Source: https://habr.com/ru/post/922061/


All Articles