milenko milenko - 7 months ago 197
Python Question

IndexError: tuple index out of range with write to txt file

I have my code

import numpy as np

a1=np.empty(10)
a1.fill(1900)

a2=np.empty(10)
a2.fill(3100)

a3=np.empty(10)
a3.fill(3600)

with open('homes.txt', 'w') as f:
for i in a1:
for j in a2:
for k in a3:
np.savetxt(f, i, j,k)


I want to write arrays to text file like this

1900. 3100. 3600.
1900. 3100. 3600.
1900. 3100. 3600.


But terminal gives me

Traceback (most recent call last):
File "m84.py", line 16, in <module>
np.savetxt(f, i, j,k)
File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 1034, in savetxt
ncol = X.shape[1]
IndexError: tuple index out of range


If my idea is wrong it would be nice that someone proposes other solution.

Answer

You can do this by writing to the file normally:

with open('homes.txt', 'w') as f:
    for i in a1:
        for j in a2:
           for k in a3:
               f.write("%f %f %f\n"%(i,j,k))

However, I am suspecting that you don't really want to do exactly this, because this will print 1000 lines (because of the nested loops). If you just want to write the arrays in a file, with each value being written once you can use savetxt, and you don't need to place it inside a loop. It can write a whole array at once, so you could do it as follows:

a = np.empty(shape = (10,3))
a[:,0].fill(1900)
a[:,1].fill(3100)
a[:,2].fill(3600)
np.savetxt("homes.txt",a)