[英]Saving an output as .txt file from for-loop for a function
I am a beginner in python and trying to save these the output for loop calculation to a .txt file. 我是python的初学者,尝试将这些输出保存以用于循环计算到.txt文件。
I have an input data with 40 columns and 300 rows. 我有40列300行的输入数据。 I am putting sample data: 我要放置样本数据:
4.3 3.4 2.3
8.5 1.0 0.0
2.4 4.2 4.5
3.9 2.1 0.5
import numpy as np
q = np.loadtxt('test.txt')
def qtot(i):
total = 0
for j in range (3):
total += q[i][j]
return total
I would like to save qtot
into an output file. 我想将qtot
保存到输出文件中。 Any help would be truly appreciated. 任何帮助将不胜感激。
You have read your 300 lines file into memory and it is a numpy array. 您已将300行文件读入内存,这是一个numpy数组。 Let's do your simple computation inside numpy and use it to save everything into a text file. 让我们在numpy中进行简单的计算,并使用它将所有内容保存到文本文件中。
import numpy as np
np.savetxt("output.txt", np.sum( np.loadtxt('test.txt'),axis=1 )[0:5] )
How does it work..... 它是如何工作的.....
Note that numpy does everything in low-level c-like code. 请注意,numpy会在类似于C的底层代码中执行所有操作。 So summing by raw for all 300 lines will be faster than a loop in python. 因此,按原始方式对所有300行进行求和将比python中的循环快。
--ADD-- - 加 -
If you want to add your results to the file, you should open it in the append mode: 如果要将结果添加到文件中,则应以附加模式打开它:
with open(output_file, "a") as fd:
np.savetxt(fd, np.sum( np.loadtxt('test.txt'),axis=1 )[0:5] )
but if you want to process multiple files inside the same run, it is better to accumulate results in the memory and save once 但是,如果要在同一运行中处理多个文件,最好将结果累积在内存中并保存一次
result = []
for fname in [list of input files]:
result.append( np.sum( np.loadtxt(fname),axis=1 )[0:5] )
np.saavetxt("output.txt", np.array(result))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.