简体   繁体   English

将循环中的数组保存到列中的一个txt文件中

[英]Save arrays from loop in one txt file in columns

I'm creating an array of zeros (587x1) in which I want to replace a zero with a one in a specific line of the array given as an index from another file. 我正在创建一个零数组(587x1),在该数组中,我想在数组的特定行中用一个零代替一个零,以作为来自另一个文件的索引。 This part works fine in my code so far. 到目前为止,这部分在我的代码中工作正常。

Afterwards, I want to save all these newly created arrays in one txt file as columns next to each other, separated by tabs. 之后,我想将所有这些新创建的数组保存在一个txt文件中,彼此相邻,以制表符分隔。 What my code does, however, is overwriting the arrays. 但是,我的代码所做的是覆盖数组。 How do I manage to append them next to each other in one file? 我如何设法将它们彼此相邻地附加在一个文件中?

Thanks a lot for your help! 非常感谢你的帮助!

Update: I managed to write all the arrays to one file, however, they are now simply printed on top of each other - how do I write them to columns appearing next to each other? 更新:我设法将所有数组都写到一个文件中,但是,现在它们只是简单地打印在彼此之上-如何将它们写到彼此相邻出现的列中?

import os
import numpy as np
participants = ['001']
for vp in participants:
   with open('file.txt') as f:
      content = f.readlines()
   content = [x.strip() for x in content]
   content = map(int, content)
f = open(outfile.txt, 'w')       
for line in content:
      with open('outfile.txt', 'a') as f:
            arr = np.zeros((587, 1), dtype = int)
            np.put(arr, [line], [1])
            np.savetxt(f, arr, fmt='%i')
f.close()

You can try this code, that adds a given (n,1) shaped array as a column to a textfile that contains a (n,m) shaped matrix of integers: 您可以尝试以下代码,该代码将给定(n,1)形状的数组作为列添加到包含整数(n,m)形状矩阵的文本文件中:

def appendAsColumn(arr):
    fileContent = np.loadtxt('outfile.txt', dtype = int, ndmin = 2)
    fileContent = np.hstack((fileContent, arr.astype(int)))
    np.savetxt('outfile.txt', fileContent, fmt='%i')

Note that this will not work for the very first entry of the file, you will need to call 请注意,这不适用于文件的第一个条目,您需要调用

np.savetxt('outfile.txt', arr, fmt='%i')

for the first column. 对于第一列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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