首页 > 解决方案 > 如何在单个 txt 文件中写入连续输出

问题描述

我正在处理多个数据文件(File_1、File_2、.....)。我希望将每个数据文件的所需输出作为新列的行值保存在同一个 txt 文件中。

我为我的第一个数据文件(File_1)尝试了以下代码。所需的输出 (Av_Age_btwn_0_to_5, Av_Age_btwn_5_to_10) 存储为输出 txt 文件 (Result.txt) 中列的行值。现在,当我使用 File_2 时,我希望将这些输出存储为同一 txt 文件的下一列的行值。然后对于 File_3,以类似的方式,我想要下一列中的输出,依此类推。

import numpy as np
data=np.loadtxt('C:/Users/Hrihaan/Desktop/File_1.txt')
Age=data[:,0]
Age_btwn_0_to_5=Age[(Age<5) & (Age>0)]
Age_btwn_5_to_10=Age[(Age<10) & (Age>=5)]
Av_Age_btwn_0_to_5=np.mean(Age_btwn_0_to_5)
Av_Age_btwn_5_to_10=np.mean(Age_btwn_5_to_10)
np.savetxt('/Users/Hrihaan/Desktop/Result.txt', (Av_Age_btwn_0_to_5, Av_Age_btwn_5_to_10), delimiter=',')

任何帮助,将不胜感激。

标签: pythonnumpy

解决方案


如果我理解正确,您的每个文件都是一列,并且您希望将它们组合成一个矩阵(每列一个文件)。

也许这样的事情可以工作?

import numpy as np

# Simulate some dummy data
def simulate_data(n_files):
    for i in range(n_files):
        ages = np.random.randint(0,10,100)
        np.savetxt("/tmp/File_{}.txt".format(i),ages,fmt='%i')

# Your file processing
def process(age):

    age_btwn_0_to_5=age[(age<5) & (age>0)]
    age_btwn_5_to_10=age[(age<10) & (age>=5)]

    av_age_btwn_0_to_5=np.mean(age_btwn_0_to_5)
    av_age_btwn_5_to_10=np.mean(age_btwn_5_to_10)

    return (av_age_btwn_0_to_5, av_age_btwn_5_to_10)

n_files = 5
simulate_data(n_files)

results = []
for i in range(n_files):
    # load data
    data=np.loadtxt('/tmp/File_{}.txt'.format(i))

    # Process your file and extract your information
    data_processed = process(data)

    # Store the result
    results.append(data_processed)

results = np.asarray(results)
np.savetxt('/tmp/Result.txt',results.T,delimiter=',',fmt='%.3f')

最后,你有这样的东西:

2.649,2.867,2.270,2.475,2.632
7.080,6.920,7.288,7.231,6.880

是你要找的吗?


推荐阅读