I have the following string of float numbers:
As you can see, there are no spaces between the numbers in this string. I am trying to make them csv. Therefore, I would like them to look like:
Is there a way to do this in python?. I tried to read the file using numpy, for example:
>>> w=numpy.loadtxt('coord', dtype='float') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 856, in loadtxt items = [conv(val) for (conv, val) in zip(converters, vals)] ValueError: invalid literal for float(): 0.621464022829E+00-.143866495639E-020.266573765475E-02-.582189744480E-07
but as there are no spaces, it is not possible. I also tried
numpy.fromfile which seems to read the file, but the it shows this:
>>> w=numpy.fromfile('coord', dtype='float') >>> w array([ 3.53728147e-057, 3.03226305e-100, 5.64351177e-038, 3.70004839e-033, 1.24395502e-047, 3.37923148e-057, 2.93531907e-086, 3.69971918e-057, 7.25394458e-043])
I would be very glad if somebody could shed some light in this problem.
Edited: The chosen answer works, but I would like to add that the solution proposed by @DSM is avery good as well:
Looks like you’re stuck with fixed-width values instead of delimited. You’ll have to slice up the string based on the character widths.
>>> s = '0.621464022829E+00-.143866495639E-020.266573765475E-02-.582189744480E-07' >>> [float(s[i:i+18]) for i in range(0, len(s), 18)] [0.621464022829, -0.00143866495639, 0.00266573765475, -5.8218974448e-08]
To read from a csv you could do something like
with open('file.csv') as f: data = [[float(line[i:i+18]) for i in range(0, len(line), 18)] for line in f.readlines()]
You could then pass this to
numpy if you want
w = numpy.array(data)