How to use python numpy.savetxt to write strings and float number to an ASCII file?
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as npnames = np.array(['NAME_1', 'NAME_2', 'NAME_3'])floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])ab['var1'] = namesab['var2'] = floatsnp.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.