numpy.savetxt "tuple index out of range"?

python

Solution

the problem is that numpy.save expect an array with some shape information, while you pass it just a number.

if you want to pass one element at the time (but I suggest you to save the whole array) you have to convert it first to a numpy array with a shape of at least one

np.savetxt(outfile, array(data_slice).reshape(1,), fmt='%1.4e')

this is because the shape of a single number is a void tuple, and to write to file it try to split along the first dimension

array(1).shape == tuple()
#True

to save the whole array it is sufficient to do:

np.savetxt(outfile, data, fmt='%1.4e')

Problem

I'm trying to write a few lines into a text file, and here's the code I used: ``` import numpy as np # Generate some test data data = np.arange(0.0,1000.0,50.0) with file('test.txt', 'w') as outfile: outfile.write('# something') for data_slice in data: np.savetxt(outfile, data_slice, fmt='%1.4e') outfile.write('# New slice\n') ``` When the code runs up to the line with savetxt, I get this error: ``` IndexError: tuple index out of range ``` Any idea why this happens? I tried removing the "fmt" part, but I get the same thing.

Original source