如何将n维数组(pythonnumpy)导出到文本文件中?

如何将n维数组(pythonnumpy)导出到文本文件中?,python,numpy,Python,Numpy,我有矩阵,它表示为二维数组。 看起来我可以使用numpy.ndarray.tofile将其导出到文本文件中,但它只在一行中生成所有内容。 如何获取矩阵格式的文本文件(例如,矩阵中的一行是一行)? 像 而不是 1 2 3 4 5 6 7 8 9 有关将numpy数组写入文件的信息,请参阅本文: 代码应该类似于: #data is a numpy array data = numpy.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]]) # Save the array

我有矩阵,它表示为二维数组。 看起来我可以使用numpy.ndarray.tofile将其导出到文本文件中,但它只在一行中生成所有内容。 如何获取矩阵格式的文本文件(例如,矩阵中的一行是一行)? 像

而不是

1 2 3 4 5 6 7 8 9

有关将numpy数组写入文件的信息,请参阅本文:

代码应该类似于:

#data is a numpy array
data = numpy.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])


# Save the array back to the file
np.savetxt('test.txt', data)
这将产生以下(几乎是人类可读的)输出:

with open('path/to/file', 'w') as outfile:
    for row in matrix:
        outfile.write(' '.join([str(num) for num in row]))
        outfile.write('\n')
#data is a numpy array
data = numpy.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])


# Save the array back to the file
np.savetxt('test.txt', data)
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
7.000000000000000000e+00 8.000000000000000000e+00 9.000000000000000000e+00