Arrays Numpy不正确地保存文本
我目前正在编写一个Python3函数,它接受一个numpy数组并将整个数组打印到一个文本文件中,但它首先在最后一行追加一个0。例如,如果我给它np.eye(3) 应该写,Arrays Numpy不正确地保存文本,arrays,python-3.x,numpy,text-files,Arrays,Python 3.x,Numpy,Text Files,我目前正在编写一个Python3函数,它接受一个numpy数组并将整个数组打印到一个文本文件中,但它首先在最后一行追加一个0。例如,如果我给它np.eye(3) 应该写, 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=ar
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这么做吗?是什么让你烦恼?您的格式指定一个长度为10个字符、带5位小数的字段。这就是你得到的:
In [357]: fmt='%10.5f'
In [358]: fmt%1
Out[358]: ' 1.00000'
In [359]: fmt%0
Out[359]: ' 0.00000'
要获得'1 0'
您需要给它一个不同的fmt
,类似于%d
。您熟悉Python格式规范吗?np.eye(3)
返回标识矩阵,即沿对角线的1()。在这种情况下,它产生的输出是正确的。
In [357]: fmt='%10.5f'
In [358]: fmt%1
Out[358]: ' 1.00000'
In [359]: fmt%0
Out[359]: ' 0.00000'