mattiav27
mattiav27

Reputation: 685

problems with numpy.savetxt

I am using python 2.6, and I am trying to write vector on a file with savetxt from numpy.

In a older program I wrote at the university, I needed to read data from a file, transform the last column from degree to radiants, and write the result on another file; this is what I came up with:

import math
import numpy as np

vec=[]  
with open("In.txt") as f:
    for line in f:
        a = float(line.split()[0])
        b = float(line.split()[1])
        c = float(line.split()[2])
        rad = math.pi/2.-(float(line.split()[3])*math.pi/180.)
        vec.append((a,b,c,rad))
np.savetxt("Out.txt",vec)

Everything went as expected: in the Out.txt I had my data dislayed correctly as a table.

Now I am trying to do something similar: I read data from a file, perform some operation, and writing the result in a file:

fout=open("Out.txt",'a')

for n in range(nsteps)
  with open("In.txt") as fin:
    for line in fin:
      #long operations: at the end I have a vector par with 4 elements
      #I want to write this vector as a new line in my output file
      np.savetxt(fout,par)
fout.close()

The problem is that in the output I have only one column:

par[0]
par[1]
par[2]
par[3]
par[0]
par[1]
...

if I write par on the terminal at every step I have it correctly displayed as:

[par[0],par[1],par[2],par[3]]
...

what am I doing wrong?

Upvotes: 0

Views: 1503

Answers (1)

theaembee
theaembee

Reputation: 69

Your list has to be in a different form (look at the brackets):

par = [[1, 2, 3, 4, 5, 6]]
np.savetext(fout, par, delimiter="\t")

Upvotes: 1

Related Questions