0

I have a for loop creating a matrix every time and I need to write all the matrices to a text file

I used np.savetxt()in the for loop, but in the end, the textfile only shows the last matrix I created.

Does anyone know what happened?

file = open("newfile.txt", "w")
for i in range (0,5):
    matrix = numpy.zeros((5, 5)) 
    np.savetxt(file, matrix)
file.close()
1

3 Answers 3

1

You need use ba other than w when you append a numpy array into a csv file. b is binary mode Without b your code will have type error. Tested on python3.5

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

Comments

0

You have to open the file in append mode:

file = open("newfile.txt", "a")

Comments

0

Flag "w" causes file to be overwitten, you should use "a", for appending.

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.