简体   繁体   English

Numpy错误地保存文本

[英]Numpy Saving Text Incorrectly

I'm currently writing a python 3 function that takes in a numpy array and prints the entire array to a text file but it first appends a 0 to the last row. 我目前正在编写一个python 3函数,该函数接受一个numpy数组并将整个数组打印到文本文件,但首先将0附加到最后一行。 For example if I give it np.eye(3), 例如,如果我给它np.eye(3),

1 0 0 
0 0 1
0 0 1

it should write, 它应该写,

1 0 0 
0 0 1
0 0 1 0

to a text file. 到文本文件。 Although the following code, 虽然下面的代码,

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

keeps returning 不断回来

   1.00000    0.00000    0.00000
   0.00000    1.00000    0.00000
   0.00000    0.00000    1.00000    0.00000

It's strange because every line is indented in the text file. 这很奇怪,因为文本文件中的每一行都缩进了。 Is there anyway to keep numpy from doing this? 无论如何,要防止numpy这样做?

what is it that bothers you? 困扰您的是什么? Your format specifies a field 10 char long, with 5 decimals. 您的格式指定了一个10字符长的字段,带有5个小数。 That's what you get: 那就是你得到的:

In [357]:  fmt='%10.5f'
In [358]: fmt%1
Out[358]: '   1.00000'
In [359]: fmt%0
Out[359]: '   0.00000'

To get '1 0 0' you need to give it a different fmt , something like %d . 要获得'1 0 0'您需要给它一个不同的fmt ,如%d Are you familiar with the Python formatting % specifications? 您是否熟悉Python格式化%规范?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM