Reading fortran double precision format in python

I am trying to read a Fortran double precision number, e.g. 1.2345D + 02, in python, but I got the following error:

>>> float('1.2345D+02') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for float(): 1.2345D+02 

Following the advice of Python scientific notation using D instead of E , I tried numpy but also get the same error:

 import numpy >>> numpy.float("1.2345D+02") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for float(): 1.2345D+02 

Does Python have a solution for reading these double-precision numbers without changing the "D" to the "E"?

EDIT: I replaced the bad syntax with strings. But still I get errors.

+6
source share
2 answers

What happened to float(str.replace("D", "E")) ?

Note that numpy DOES supports fortran notation: numpy.float("1.2345D+02") .

You seem to have a deeper goal, perhaps shedding light on this will help.

+4
source

Substitution can be done more carefully using a regular expression:

 import re re_dbl_fort = re.compile(r'(\d*\.\d+)[dD]([-+]?\d+)') text = 'DEW=[0.242D+03 -4.320D-06]' re_dbl_fort.sub(r'\1E\2', text) # DEW=[0.242E+03 -4.320E-06] 

Or, if you have a list of lines (lines) read from a file using readlines() :

 lines = ['REPORT CARD\n', 'GRADE: D+ (1.3D+00/4.0D+00)\n'] for ln, line in enumerate(lines): res = re_dbl_fort.sub(r'\1E\2', line) if line != res: lines[ln] = res # ['REPORT CARD\n', 'GRADE: D+ (1.3E+00/4.0E+00)\n'] 
+1
source

Source: https://habr.com/ru/post/888011/


All Articles