Python:将数组逐行写入文件

Python: Write array to file row by row

我有一个文件,内容为

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')

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

我认为您误解了 'append' 的意思。当您将数据附加到文件时,这意味着垂直附加:将内容添加到文件末尾。如果你想做水平追加,你首先必须读入数据,然后再写回所有内容。

import numpy as np

mydata = np.matrix(list(range(1, 16)))
array_from_list=(mydata.reshape(3, 5))
x_transpose = (np.transpose(array_from_list))   # the array above

with open('5rows.txt','r') as f:
    lines = list(f)
with open('5rows.txt','w') as f:
    for existing, new in zip(lines[:16], x_transpose):
        f.write('{}\t{}\n'.format(existing, '\t'.join(new)))

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

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

np.savetxt 写入一个 csv 文件。在这种情况下,诀窍是 assemble 你的两个 arrays/lists 成一个复合数组,然后根据需要格式化它:

In [100]: mydata = np.arange(1,16).reshape(3,5)
In [101]: mydata
Out[101]: 
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15]])
In [102]: mydata = np.arange(1,16).reshape(3,5).T
In [103]: mydata
Out[103]: 
array([[ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14],
       [ 5, 10, 15]])
In [104]: elements = np.arange(18,31,3)
In [105]: elements
Out[105]: array([18, 21, 24, 27, 30])
In [106]: arr = np.column_stack((elements, mydata))
In [107]: arr
Out[107]: 
array([[18,  1,  6, 11],
       [21,  2,  7, 12],
       [24,  3,  8, 13],
       [27,  4,  9, 14],
       [30,  5, 10, 15]])
In [108]: np.savetxt('test.txt',arr, fmt='%2d   %3d %3d %3d')
In [109]: cat test.txt
18     1   6  11
21     2   7  12
24     3   8  13
27     4   9  14
30     5  10  15

等效地,我可以 zip 到两个数组;将 row 个值组合成一个元组,并格式化为:

In [112]: for e, d in zip(elements, mydata):
     ...:     ed = (e,)+tuple(d)
     ...:     print('%2d   %3d %3d %3d'%ed)
              # print(('%d  '%e) + ' '.join(['%3d']*3)%tuple(d))
     ...:     
18     1   6  11
21     2   7  12
24     3   8  13
27     4   9  14
30     5  10  15

我正在使用 print,但您可以将其切换为文件写入。