0

I am using python 2.7. I tried to store 2d arrays in file, but it stored only recent value. Suppose if I enter values for 3 arrays which are of 4 rows and two columns then it just store recent single value which i entered for last array. I used numpy for taking input for array. I tried this code:

import numpy as np
from math import *

def main ():
    i_p = input("\n Enter number of input patterns:")
    out = raw_input("\n Enter number of output nodes:")
    hidden = raw_input("\n Enter number of hidden layers:")
    print 'Patterns:'
    for p in range(0,i_p):
        print "z[%d]"%p

        rows=input("Enter no of rows:")
        cols=input("Enter no of coloumns:")
        ff=open('array.txt','w')
        for r in range(0,rows):
            for c in range(0,cols):
                z=np.matrix(input())
                ff.write(z)
                np.savetxt('array.txt',z)



if __name__=="__main__":
    main()
3
  • 1
    Ident your code properly, please Commented Dec 31, 2015 at 6:33
  • You are opening your file (with the same file name) inside a for loop. Every time the loop runs, the file will be overwritten with new content. Commented Dec 31, 2015 at 7:35
  • so how to solve this problem? Commented Dec 31, 2015 at 8:31

1 Answer 1

2

Your

np.savetxt('array.txt',z)

opens the file for a fresh write; thus it destroys anything written to that file before.

Try:

ff=open('array.txt','w')
for i in range(3):
    z = np.ones((3,5))*i
    np.savetxt(ff,z)

This should write 9 lines, with 5 columns

I was going to adapt your:

  for r in range(0,rows):
      for c in range(0,cols):
          z=np.matrix(input())
          np.savetxt...

But that doesn't make sense. You don't write by 'column' with savetxt.

Go to a Python interpreter, make a simple array (not np.matrix), and save it. Make several arrays and save those. Look at what you saved.

Sign up to request clarification or add additional context in comments.

3 Comments

instead of using z = np.ones((3,5))*i can i use z=np.matrix(input()) bcoz i want to take generalize input from the user.
i m trying to implement sample example for back-propagation algorithm from artificial neural network using python.so i tried above code for taking inputs for the neurons.i want to make it generalize code
np.matrix(input()) may work because matrix accepts a MATLAB like string expression. But it is not normally used in numpy. And since you are quite new to numpy I would not recommend going that route.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.