I am quite new to Python. I am trying to read an unformatted Fortran file by using Python. However, I would like to structure the elements read into arrays. I prepared for you a sample to help you understand my problem. Here below you can find a Fortran writer which writes three integers and then a line with three double precision elements.
program writer
integer :: dummy,dummy2,dummy3
double precision,dimension(3) :: dummy_double
dummy=1
dummy2=2
dummy3=3
dummy_double(1)=4.23e0
dummy_double(2)=5.4e0
dummy_double(3)=7.61e0
open(100,file="binary",form="unformatted",convert="little_endian")
write(100) dummy
write(100) dummy2
write(100) dummy3
write(100) dummy_double(1:3)
close(100)
end
I now want to read this file with Python without using numpy. I am aware of the INTEGER*4 at the end and beginning of each record. I skip the first 4 bits at the beginning of the file, then I read the first integer, then I skip 8 bits (end+begin) and so on. No separator is written in a same sequence, that is the double precision are not separated by an INTEGER*4 (correct me if I am wrong..). I am writing to you because I am not able to read the last line, with the 3 double precision records. I would like to store them in the comp[3] array.
import struct
with open("binary", "rb") as f:
# while True:
dummy = f.read(4)
print "dummy=",struct.unpack('i', f.read(4))[0]
dummy = f.read(8)
print "dummy2=",struct.unpack('i', f.read(4))[0]
dummy = f.read(8)
print "dummy3=",struct.unpack('i', f.read(4))[0]
comp = [0] * 3
print "length=",len(comp)
dummy = f.read(8)
comp=struct.unpack('<d', f.read(8))[0:2]
print "comp=",comp[0],comp[1],comp[2]
The error I am getting is the following:
$carlo: python Script_Library.py
dummy= 1
dummy2= 2
dummy3= 3
length= 3
comp= 4.23000001907
Traceback (most recent call last):
File "Script_Library.py", line 14, in <module>
print "comp=",comp[0],comp[1],comp[2]
IndexError: tuple index out of range
Integers are correctly read as well as the first double precision elements. However, they are not correctly stored. Would you please correct the parts of the script which are not working?
print "comp="+comp[0]+comp[1]+comp[2]. I guess the problem is that Python reads your code like(print "comp="), comp[0], comp[1], comp[2]. I'm not sure because I haven't write in Python2 for a long time and Python3 has different print syntax. But give it a try.comp=struct.unpack('<ddd', f.read(24)).compwill become a tuple with three numbers.struct.unpack()always returns tuple, even if there is only a single element.