Python:将数组逐行写入文件

标签 python file numpy string-formatting

我有一个文件,内容为

18
21
24
27
30

以及数组

[[ 1  6 11]
 [ 2  7 12]
 [ 3  8 13]
 [ 4  9 14]
 [ 5 10 15]]

如何将此数组写入文件,以便每一行都与适当的行相对应,例如它变成这样:

18    1  6 11
21    2  7 12
24    3  8 13
27    4  9 14
30    5 10 15

我已经使用了这段代码,但是它并没有按照我想要的方式编写代码。代码:

import numpy as np

    ourlist = []
    for i in range(1, 16):
        ourlist.append(i)


    mydata = np.matrix([ourlist])
    array_from_list=(mydata.reshape(3, 5))
    x_transpose = (np.transpose(array_from_list))   # the array above

    with open('5rows.txt','a') as f:                #the file containing numbers
     for elements in x_transpose:
         f.write(str(elements))
         f.write('\n')

它将元素写入行尾。如果可能的话,您能告诉我该怎么做吗?我非常感谢您的帮助!

最佳答案

下面的代码可能会解决您的问题,尽管它的性能不是很好。您也许可以改进解决方案以更好地满足您的需求。

import numpy as np

ourlist = []

for i in range(1, 16):
    ourlist.append(i)


mydata = np.matrix([ourlist])
array_from_list=(mydata.reshape(3, 5))
x_transpose = (np.transpose(array_from_list))

with open('file.txt', 'r') as f:
    lines = f.readlines()

with open('file.txt', 'w') as f:
    i = 0
    for line in lines:
        f.write(str(int(line)) + "  " + str(x_transpose[i])[1:-1][1:-1] + "\n")
        i+=1

关于Python:将数组逐行写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44490630/

相关文章:

python - Python 中的 LDA,我得到的是字符而不是主题

python - 如何在Python中打印文件中的单词

python - 如何从 FiPy 中的 3D 变量中提取平面(3D 到 2D)

python - 数组中所有一维点与 python diff() 之间的区别?

android - 删除数据库文件夹内部存储

python - 查找 numpy 数组中每一行的最大值以及另一个相同大小的数组中的对应元素

python - 简单的 Pytorch 示例 - 训练损失并没有减少

python - 二维日期时间分组依据

python matplotlib条形图添加条形标题

jquery - 最新的 jquery 等效文件上传而无需刷新页面