convert FORTRAN exponential format text to float
I need to convert numbers read from a text file to floating point. The numbers are in the format 1.538D-06 (written by a FORTRAN application) and have varying amounts of whitespace between them from line to line. The function fromstring() deals with the whitespace just fine but 'dtype=float' doesn't correctly convert the data. It sees every thing up to the 'D' and ignores the rest(I assume expecting an 'e' to indicate the exponential). I was able to get around this using re.sub() to change the 'D' to 'e' in the string before using fromstring(), but I was wondering if python has any way to directly read this data as float? Google didn't find an answer.
Did you try loadtxt? I try to output something in the format 1.538D-06 with Fortran in order to test reading it with loadtxt, but I always get 1.538E-06. Where does the 'D' come from?
program write_txt real(kind=8):: x open(10,file='data.txt') do i = 1,10 x = i*2. write(10,fmt='(2(D12.3))') x,x**2 enddo close(10) end program write_txt In [1]: x,y = loadtxt('data.txt',unpack=True) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/dfroger/tmp/<ipython console> in <module>() /usr/lib/python2.5/site-packages/numpy/lib/io.pyc in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack) 350 351 # Convert each value according to its column and store --> 352 X.append(tuple([conv(val) for (conv, val) in zip(converters, vals)])) 353 354 if len(dtype_types) > 1: ValueError: invalid literal for float(): 0.200D+01 Maybe the the arguments 'converters' of loadtxt can help?
program write_txt real(kind=8):: x open(10,file='data.txt') do i = 1,10 x = i*2. write(10,fmt='(2(D12.3))') x,x**2 enddo close(10) end program write_txt In [1]: def expDtofloat(s): ...: return float(s.replace('D','E')) ...: In [2]: x,y = loadtxt('data.txt',unpack=True,converters={0:expDtofloat,1:expDtofloat}) Not really better than re.sub() ...
On Wed, 2010-09-29 at 16:36 +0200, David Froger wrote:
Did you try loadtxt? I try to output something in the format 1.538D-06 with Fortran in order to test reading it with loadtxt, but I always get 1.538E-06. Where does the 'D' come from?
No, I didn't, but I will. Preserving the 'D' isn't important, only proper conversion of the string to float. The data was created by an atmosphere modeling program called AMOEBA that was written in FORTRAN.
_______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion
participants (2)
-
David Froger
-
Thomas Kirk Gamble