Python: reading a Fortran binary using numpy or scipy

I am trying to read a fortran file with headers as integers, and then the actual data as a 32 bit float. Using numpy fromfile('mydatafile', dtype=np.float32), it reads the whole file as float32, but I need the headers that will be in int32 for my output file. Using scipy FortranFile, it reads the headers:

f = FortranFile('mydatafile', 'r')
headers = f.read_ints(dtype=np.int32)

but when i do this:

data = f.read_reals(dtype=np.float32)

it returns an empty array. I know that it should not be empty, because using numpy fromfile it reads all the data. Oddly enough, the scipy method worked for other files in my dataset, but not in that. Perhaps I do not understand the difference between each of the two reading methods with numpy and scipy. Is there a way to isolate the headers ( dtype=np.int32) and data ( dtype=np.float32) when reading in a file in any way?

+4
source share
2 answers

np.fromfile "count", , . , , - , - , :

with open('filepath','r') as f:
    header = np.fromfile(f, dtype=np.int, count=number_of_integers)
    data = np.fromfile(f, dtype=np.float32)
+4

@DavidTrevelyan . - fortranfile struct. , scipy fortranfile.

, . :

from fortranfile import FortranFile
from struct import unpack

with FortranFile(to_open) as fh:
    dat = fh.readRecord()
    val_list = unpack('=4i20d'.format(ln), dat)

pip install fortranfile. struct , (un) pack .

0
source

All Articles