简体   繁体   English

将输出从for循环保存为.txt文件

[英]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..... 它是如何工作的.....

  1. np.load - loads the file and it is 2d array np.load-加载文件,它是二维数组
  2. np.sum - sums elements in the array, but axis=1 tells numpy that sum should go in raws so it returns an array with the same number of elements as lines in your file np.sum-对数组中的元素求和,但是axis = 1告诉numpy sum应该以raws开头,因此它返回一个数组,该数组的元素数与文件中的行数相同
  3. [0:5] - cuts down this array to just the first five elements. [0:5]-将这个数组缩减为仅前五个元素。 You can use slices or tuples to cut required lines from the array 您可以使用切片或元组从数组中剪切所需的行
  4. np.savetxt - saves it into a file np.savetxt-将其保存到文件中

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.

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