Read numbers without spaces in text-file with ython
Question: I'm a newbie with Python and struggle to read a text file like this:

    
    
      0.42617E-03-0.19725E+09-0.21139E+09 0.37077E+08
      0.85234E-03-0.18031E+09-0.18340E+09 0.28237E+08
      0.12785E-02-0.16583E+09-0.15887E+09 0.20637E+08
    

There are thus no comma or space delimiters between the numbers in the file.
With Matlab I know how to specify the formats, but how to do it in Python?

I have been trying np.loadtxt but don't know how to set number of digits to
read, so if anyone could give me a hint on this I would be much grateful.

Thanks in advance, Erik


Answer: To expand on my comment, based on the fact that you can successfully parse
this with MATLAB, I assume that these fields are fixed width. In that case,
you can just slice each row based on the field width, and then convert that to
a numpy array if that's what you need. As an example:

    
    
    import numpy
    
    input_data = """ 0.42617E-03-0.19725E+09-0.21139E+09 0.37077E+08
     0.85234E-03-0.18031E+09-0.18340E+09 0.28237E+08
     0.12785E-02-0.16583E+09-0.15887E+09 0.20637E+08
    """
    input_rows = input_data.split('\n')
    
    width = 12
    num_fields = 4
    
    data = []
    for input_row in input_rows:
        if not input_row:
            continue
        data.append([float(input_row[width * i:width * (i + 1)].strip()) for i in range(num_fields)])
    
    data = numpy.array(data)
    print(data)
    

This outputs:

    
    
    [[  4.26170000e-04  -1.97250000e+08  -2.11390000e+08   3.70770000e+07]
     [  8.52340000e-04  -1.80310000e+08  -1.83400000e+08   2.82370000e+07]
     [  1.27850000e-03  -1.65830000e+08  -1.58870000e+08   2.06370000e+07]]
    

Of course, this example uses a fixed string to represent the input data, but
you can imagine doing a similar thing with your input stream.

