简体   繁体   中英

save output of each iteration of for loop in single file

hii experts i have a text file(input.txt) that contain 5 columns data as given below:

2 3 4 5 6
3 4 5 6 7
2 3 4 5 6 
6 7 8 9 0
3 3 3 3 3

i just want to read single column at each iteration and want to add 5 on it and want np.savetxt to save each iteration output of the loop in different column of a text file

i wrote the script

import numpy as np
import random


inpdata=np.loadtxt("input.txt")
for x in np.arange(0,4,1):
        data=inpdata[:,x]
        sum=data+5
        np.savetxt('tx_'+str(x),data)

while doing this output are saved in different files but i need output to be saved in single file as firstcolumn,second column, third column.... i need output like as below

7  8  9  10  11
8  9  10 11  12
7  8  9  10  11 
11 12 13 14  5
8  8  8  8   8

i hope some expert will help me .Thanks in advance.

Since you just perform some manipulation on an array. You could equivalently do the following:

  1. read the data from the txt file
  2. perform whatever operation you want to do column-wise or any other.
  3. save the new data to file

In this specific example, you could just add a scalar to you array like the following:

import numpy as np
data=np.loadtxt("test.txt")
data += 5
np.savetxt('output.txt', data)

And if you insist to do it column-wise:

import numpy as np
data=np.loadtxt("test.txt")
for i in range(data.shape[1]):
    data[:, i] += 5
np.savetxt('output.txt', data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM