user2095624
user2095624

Reputation: 381

savetxt save only last loop data

Can someone please explain?

import numpy

a = ([1,2,3,45])
b = ([6,7,8,9,10])
numpy.savetxt('test.txt',(a,b))

This script can save well the data. But when I am running it through a loop it can print all but cannot not save all. why?

import numpy

a = ([1,2,3,4,5])
b = ([6,7,8,9,10])
for i,j in zip(a,b):
    print i,j
    numpy.savetxt('test.txt',(i,j))

Upvotes: 0

Views: 2457

Answers (5)

el Josso
el Josso

Reputation: 152

The faster way will be to use open with

import numpy

a = ([1,2,3,4,5])
b = ([6,7,8,9,10])

with open('test.txt','wb') as ftext:  #Wb if you want to create a new one,
    for i,j in zip(a,b):              #ab if you want to appen it. Her it's wb
        print i,j
        numpy.savetxt(ftext,(i,j))

It will be really faster with a large array

Upvotes: 1

jamylak
jamylak

Reputation: 133664

import numpy as np

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

np.savetxt('test.txt', np.column_stack((a, b)))

Upvotes: 0

Vahid Rafiei
Vahid Rafiei

Reputation: 382

You should append (i,j) rather than overwriting previous ones

Upvotes: 0

lucasg
lucasg

Reputation: 11012

You overwrite the previous data each time you call numpy.savetext().

A solution, using a temporary buffer array :

import numpy

a = ([1,2,3,4,5])
b = ([6,7,8,9,10])

out = []

for i,j in zip(a,b):
   print i,j
   out.append( (i,j) )

numpy.savetxt('test.txt',out)

Upvotes: 4

unkulunkulu
unkulunkulu

Reputation: 11922

numpy.savetxt will overwrite the previously written file, so you only get the result of the last iteration.

Upvotes: 2

Related Questions