1

I have matrix , which presented as 2 dimensional array. It seems like I can use numpy.ndarray.tofile to export it into text file, but it just generate everything in one line. How can I get text file in matrix format(say, one line is one row in matrix)? like

1 2 3
4 5 6
7 8 9

instead of

1 2 3 4 5 6 7 8 9

2 Answers 2

4

Consult this post about writing numpy arrays to files: Write multiple numpy arrays to file

The code should be something like:

#data is a numpy array
data = numpy.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])


# Save the array back to the file
np.savetxt('test.txt', data)

This yields the following (almost human-readable) output:

1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
7.000000000000000000e+00 8.000000000000000000e+00 9.000000000000000000e+00
Sign up to request clarification or add additional context in comments.

Comments

-1
with open('path/to/file', 'w') as outfile:
    for row in matrix:
        outfile.write(' '.join([str(num) for num in row]))
        outfile.write('\n')

Comments

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.