Home > Back-end >  How to save values in row after one loop?
How to save values in row after one loop?

Time:03-10

How to save values to row in one cycle, please?

import numpy as np

A = 5.4654
B = [4.78465, 6.46545, 5.798]

for i in range(2):
    f = open(f'file.txt', 'a')               
    np.savetxt(f, np.r_[A, B], fmt='".16f') 
    f.close()

The output is:

5.4653999999999998
4.7846500000000001
6.4654499999999997
5.7980000000000000
5.4653999999999998
4.7846500000000001
6.4654499999999997
5.7980000000000000

The desired output is:

5.4653999999999998     4.7846500000000001     6.4654499999999997    5.7980000000000000
5.4653999999999998     4.7846500000000001     6.4654499999999997    5.7980000000000000

CodePudding user response:

According to the documentation:

newlinestr, optional
String or character separating lines.

So, perhaps:

np.savetxt(f, np.r_[A, B], fmt='".16f', newlinestr=' ')
print('\n', file=f)

An alternative might be to np.transpose(np.r_[A, B]) perhaps?

  • Related