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
    Possible duplicate of [How do you append to a file in Python?](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) – Bamcclur Nov 08 '16 at 20:01

3 Answers3

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

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
0

You have to open the file in append mode:

file = open("newfile.txt", "a")
damores
  • 2,251
  • 2
  • 18
  • 31
0

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

Ada Borowa
  • 79
  • 1
  • 2