【发布时间】:2016-02-11 23:20:49
【问题描述】:
我目前正在编写一个 python 3 函数,该函数接受一个 numpy 数组并将整个数组打印到一个文本文件,但它首先将 0 附加到最后一行。例如,如果我给它 np.eye(3),
1 0 0
0 0 1
0 0 1
它应该写,
1 0 0
0 0 1
0 0 1 0
到一个文本文件。虽然下面的代码,
def addTo(array,textFile):
file=open(textFile,'ab')
(numRows,numColumns)=array.shape
main=array[0:numRows-1,:]
endRow=array[numRows-1,:]
newEndRow=np.append(endRow, [0])
np.savetxt(file,main, fmt='%10.5f', newline=os.linesep)
np.savetxt(file,newEndRow[np.newaxis], fmt='%10.5f', newline=os.linesep)
file.close()
addTo(np.eye(3),'test1.txt')
不断返回
1.00000 0.00000 0.00000
0.00000 1.00000 0.00000
0.00000 0.00000 1.00000 0.00000
这很奇怪,因为文本文件中的每一行都是缩进的。有没有办法阻止 numpy 这样做?
【问题讨论】:
-
np.eye(3)返回单位矩阵 - 沿对角线 (en.wikipedia.org/wiki/Identity_matrix) 为 1。在这种情况下,它产生的输出是正确的。
标签: arrays python-3.x numpy text-files