Search code examples
pythonnumpyfortranbinaryfiles

Read in Fortran a matrix saved with tobytes in Python


I saved a matrix in Python with ndarray.tobytes(order='F').

f_mat = open('mat.dat', 'wb')
f_mat.write(matrix.tobytes('F'))
f_mat.close()

Is there a quick way to read it in Fortran or should I do a for cycle and figure out the order of the elements?


Solution

  • If you know the size (n time m) and the type of the array and declare it accordingly:

    !just an example
    real(c_double), allocatable :: mat(:,:)
    allocate(mat(n,m))
    

    it should be just

    open(newunit = u, file='mat.dat', access='stream', form='unformatted', status='old', action='read')
    read(u) mat
    close(u)
    

    The arguments to open after access='stream' are optional.