I found myself struggling with this problem very frequently so I wrote a function which generates a header and formatting string to use with np.savetxt
:
You can find the code on GitHub Gist.
I haven't tested it extensively but it can deal with most data types and generates (optionally) automatically padded output. The output is nicely formatted and human readable, support drag-and-drop into excel can be read back easily as well where the field names and dtypes are autodetected (mostly).
Sample output:
# x y1 y2 bools verylongnamewithshortcontent bytes objects
0 -25 3.9e+03 1 a b'AvvOkBhFJZIUQsxdg' {'key1': 12423, 'key2': 'asdfjkl;'}
1 255 8e+03 1 a b'SxKvotv' {'key1': 12423, 'key2': 'asdfjkl;'}
2 -211 2.5e+03 0 a b'tvBQXgqqS' {'key1': 12423, 'key2': 'asdfjkl;'}
3 -830 5.7e+02 1 a b'NCFrZHfniaZjeUg' {'key1': 12423, 'key2': 'asdfjkl;'}
4 -3468 8.7e+03 0 a b'RxzuvyKCxKBsz' {'key1': 12423, 'key2': 'asdfjkl;'}
5 4644 2.2e+03 1 a b'yHijSVfCv' {'key1': 12423, 'key2': 'asdfjkl;'}
6 27946 4e+03 0 a b'ywyZeQICJrY' {'key1': 12423, 'key2': 'asdfjkl;'}
7 313770 3.2e+03 1 a b'HBEufqJuASVxHRIxpjd' {'key1': 12423, 'key2': 'asdfjkl;'}
8 -76304 7.7e+02 0 a b'UX' {'key1': 12423, 'key2': 'asdfjkl;'}
9 427810 8.4e+03 0 a b'jmnOEWCvTWg' {'key1': 12423, 'key2': 'asdfjkl;'}
Input / Output dtypes:
[('x', '<i4'), ('y1', '<i4'), ('y2', '<f8'), ('bools', '?'), ('verylongnamewithshortcontent', '<U7'), ('bytes', 'S20'), ('objects', 'O')]
[('x', '<i4'), ('y1', '<i4'), ('y2', '<f8'), ('bools', '<i4'), ('verylongnamewithshortcontent', '<U1'), ('bytes', '<U22'), ('objects', '<U35')]