0

I have the following fortran code that I used to create a binary unformatted file:

PROGRAM main_program
    
    implicit none

    open (10, form='unformatted', file='myFile.xyz')
        write(10) 1
        write(10) 400, 400, 1
            write(10) 1.0d0, 1.25d0, 1.50d0, 1.75d0, 2.0d0, 2.25d0
            write(10) 3.0d0, 3.25d0, 3.50d0, 3.75d0, 4.0d0, 4.25d0, 4.50d0, 4.75d0, 5.00d0
    close(10)
    
END

I want to read the generated 'myFile.xyz' from the above program using python. For some reason maybe because of the way the fortran formats the file writup, reading this file does not seem straightforward in python. Here is a python code that I have tried:

import numpy as np

file_path = "myFile.xyz"

# Read the binary file using numpy
with open(file_path, "rb") as file:
    data = np.fromfile(file, dtype=np.float64)

# Extract the first three integers (data[0:3])
integers_data = data[:3]

# Extract the double-precision floating-point values (skip the first 3 integers)
float_values = data[3:]

# Output the extracted data
print("The first three integers in the binary file are:", integers_data)
print("The double-precision floating-point values in the binary file are:", float_values)

How could I read myFile.xyz in python?

I tried different index ranges for the variable and printed the output. Nothing seem to work properly.

  • 5
    Can you change the Fortran program to use 'stream' access? If not, you'll need to write a Python program which accounts for all the non-portable/compiler-dependent effects which are associated with record-based files. (There's are _lots_ of questions here about that.) – francescalus Jul 19 '23 at 09:03
  • Unfortunately I can't use the 'stream' option. I need record markers for other purposes. – Prof. Dumbledore Jul 19 '23 at 11:40
  • 3
    If you need to rely on record markers for other purposes, then why doesn't your Python program take them into account? The first record in the file consists of one integer, the second three, but the Python seems to want to assume there are just three integers in total? You can start with [this other question](https://stackoverflow.com/q/8131204/3157076), and the look for others, but Fortran unformatted sequential files are wholly unsuited for portable data interchange. – francescalus Jul 19 '23 at 11:48
  • I've had some success with the `scipy.io` library. See my answer to an earlier question here: https://stackoverflow.com/questions/53639058/reading-fortran-binary-file-in-python/53646572#53646572 – chw21 Jul 19 '23 at 12:11
  • Do you have to use numpy or can you use something like struct? Is this on Linux or Windows? Which Fortran compiler are you using? If you are on Linux, use od -x to look at the file. Once you know the structure, it is quite easy to read the data. – cup Jul 22 '23 at 23:31

0 Answers0