Reputation: 61
I am trying to write two strings into a .txt file using numpy.savetxt(). I want the strings to be on consecutive lines. However, when I run my code, I get the following error:
ncol = X.shape[1]
IndexError: tuple index out of range
Which occurs at the first line I call np.savetxt(). My code is below:
import numpy as np
data=np.loadtxt('data.txt')
name1 = 'James'
name2 = 'James 2'
hi = 'Hello {}'.format(name1)
bye = 'Goodbye {}'.format(name2)
np.savetxt('greet.txt', hi, fmt="%s", newline='\n')
np.savetxt('greet.txt', bye, fmt="%s")
I've tried it without fmt, changing '%s' to other things, but they all give me the same error. Can anyone tell me what I'm doing wrong?
Upvotes: 0
Views: 1080
Reputation: 763
According to the @moses-koledoye comment and @jvnna's answer, the following is the correct answer.
The hi
and bye
variables are of type string
hi = 'Hello {}'.format(name1)
bye = 'Goodbye {}'.format(name2)
You are trying to save them to a txt file with the numpy function np.savetxt
, according to the documentation:
Save an array to a text file.
So the hi
and bye
variables must be of type np.array
in order to be handled with that function. Also, some reshape is needed.
A snippet code that does the trick could be:
hi = 'Hello {}'.format(name1)
bye = 'Goodbye {}'.format(name2)
hi = np.array(hi).reshape(1, ) # This does the trick for hi
bye = np.array(bye).reshape(1, ) # This does the trick for bye
np.savetxt('greet.txt', hi, fmt="%s", newline='\n')
np.savetxt('greet.txt', bye, fmt="%s")
Upvotes: 0