简体   繁体   中英

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. For example if I give it 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?

what is it that bothers you? Your format specifies a field 10 char long, with 5 decimals. 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 . Are you familiar with the Python formatting % specifications?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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