对一堆文件进行平均处理



我有1000个文件,每个文件有6列1000点的信息。我想在1000个时间步长中为每个点计算第6列的平均值。我的意思是,对于每一点,我希望平均有1000个时间步长,然后保存在一个文本文件中。我编写的代码在理解流程方面存在问题。它可以计算每个点的平均值,但最后,它给了我一个数字。

import os
import numpy as np
l = [f for f in sorted(os.listdir('.')) if f.startswith('config')]

maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in l])
l = ['configuration_%d.out' % i for i in range(maxnum)]

for i, d in enumerate(l): 
    a = np.loadtxt(d).T 
    num = os.path.splitext(d)[0]
    #j = np.zeros(1001)
    x = np.mean(a[5])
    #y = np.mean(a[4])
    np.savetxt("foo.txt",x)

如果你能帮我一个忙,我将不胜感激。感谢所有

在回答您的问题时,您每次都会覆盖foo.txt,因此您只能看到一个数字。

在循环之前打开一个txt文件,然后只添加信息:

txt_file = open('foo.txt', 'w')
for i, d in enumerate(l):
     txt_file.write(f'{x}n')
txt_file.close()

两件事:

  1. f"这是一个f字符串,可从python3.6中使用。如果您使用的是旧版本,只需根据需要格式化字符串即可
  2. \n的意思是新行,所以你把每个数字都写在下一行

最新更新