CubeBot88
CubeBot88

Reputation: 1110

Numpy matrix from text file

I am writing a matrix into a text file and need to read the file in another python script. The second script needs to get the text back into a numpy array. I have been struggling to find out how to do this, any help would be greatly appreciated. Two examples of the array are given below:

[[ 0.  0. -0.]
 [ 0.  0.  0.]
 [ 0.  0. -0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

or

[[ 0.          0.         -0.03011621]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.          0.        ]
 [ 0.          0.         -0.06023241]
 [ 0.          0.         -0.01204648]]

Upvotes: 1

Views: 596

Answers (1)

unutbu
unutbu

Reputation: 879103

To save to a text file, use np.savetxt

In [115]: x = np.zeros((10, 3))

In [116]: np.savetxt('/tmp/test.out', x)

To load, use np.loadtxt or np.genfromtxt:

In [117]: y = np.genfromtxt('/tmp/test.out')

In [120]: y.shape
Out[120]: (10, 3)

Upvotes: 2

Related Questions