2

I'm generating a binary data using a Fortran code. How can I read this data, convert it to float and plot it in Python?

I have the following code in Fortran90 that outputs the vector u data in a binary file.

program test
implicit none
  integer :: i, n
  real, allocatable :: u(:)

  n = 720
  allocate(u(0:n))

  !Set the data
  do i = 0, n
    u(i) =  exp(-(i-360.0)**2/200.0)
  end do

  !Save the data in a binary file
  open(3,file='exp.dat',form='unformatted',access='sequential')
  write(3) u
  close(3)

  deallocate(u)  
end program test

Then I ran this program and got a binary file called 'exp.dat'. I wrote the following script in Python3 to read the data from 'exp.dat' and convert it to float.

import numpy as np
filename = 'exp.dat'
data = np.fromfile(filename, 'float32')
print(np.shape(data))

However, when I run this script I get

(723,)

I would expect (721,) since we wrote the values of a vector of length 721 in 'exp.dat'. After looking at the values in the variable data, I realized that the convertion from bytes to float is not working properly. I also tried to see how this script works for a different set of datas and I got the same thing.

How can I fix it? Is there an easy way to read and convert this binary data to float?

5
  • An easy check is the length of the file in the filesystem... presumably it should be 721*4 bytes, if floats take 4 bytes. Commented Aug 21, 2019 at 21:29
  • If I create a 2884 byte file like this dd if=/dev/zero bs=721 count=4 > exp.dat and run your code, I get a shape of (721,) so I suspect your Fortran... Commented Aug 21, 2019 at 22:07
  • Please use tye generic tags for languages like fortran and python. Many more people will see your question and they will be the right people (Fortran or other tag followers). Add a version tag if the question is version-specific. Commented Aug 22, 2019 at 7:05
  • Fortran sequential files contain record markers. Use stream or direct files to store data without markers, we have duplicates. Commented Aug 22, 2019 at 7:07
  • 1
    Possible duplicate of Fortran unformatted file format and stackoverflow.com/questions/48312718/… Commented Aug 22, 2019 at 7:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.