Mahdi Kooshkbaghi Mahdi Kooshkbaghi - 15 days ago 6
Python Question

Reading default output of Fortran in Python

I have an output from old code in Fortran 77. The output is written with

write(NUM,*)


line. So basically, default format. Following is part of output:

1.25107598E-67 1.89781536E-61 1.28064971E-94 5.85754394-118 8.02718071E-94


I had a post-processing tool written in F77 and
READ(NUM,*)
read the input file correctly as:

1.25107598000000E-67 1.89781536000000E-61 1.28064971000000E-94 5.85754394000000E-118 8.02718071000000E-94


The problematic number is
5.85754394-118
.
It will read correctly as it means
5.85754394E-118
in F77.

However, now I wrote a post-processing in python and I have a following line of code:

Z = numpy.fromstring(lines[nl], dtype=float, sep=' ')


which will read an output line by line (through loop on
nl
).
But when it reaches the
5.85754394-118
number it will stop reading, going to the next line of output and basically reading wrong number. Is there any way to read it in a correct way (default way of Fortran)?
I will guess I need to change
dtype
option but not have any clue.

Answer

You can post-process your output efficiently with a regular expression:

import re

r = re.compile(r"(?<=\d)\-(?=\d)")

output_line = "1.25107598E-67  1.89781536E-61  1.28064971E-94  5.85754394-118  8.02718071E-94 "
print(r.sub("E-",output_line))

result:

1.25107598E-67  1.89781536E-61  1.28064971E-94  5.85754394E-118  8.02718071E-94 

(?<=\d)\-(?=\d) performs a lookbehind and lookahead for digits, and search for single minus sign between them. It replaces the minus sign by E-.