2016-02-12 28 views
22

Sto cercando di salvare una matrice NumPy (NX3, float64) in un file txt con numpy.savetxt:numpy.savetxt risultante un errore di formattazione mancata corrispondenza in python 3.5

np.savetxt(f, mat, fmt='%.5f', delimiter=' ') 

Questa linea ha lavorato in python 2.7 , ma in Python 3.5, sto ottenendo il seguente errore:

TypeError: Mismatch between array dtype ('float64') and format specifier ('%.5f %.5f %.5f')

Quando sto passo nel codice savetxt, la stampa l'errore (traceback.format_exc()) nel blocco catch (numpy.lib .npyio, riga 1158), l'errore è completamente diverso:

TypeError: write() argument must be str, not bytes

La riga di codice risultante eccezione è il seguente:

fh.write(asbytes(format % tuple(row) + newline)) 

ho cercato di rimuovere le asbytes, e sembra per correggere questo errore. È un bug in numpy?

risposta

23

savetxt apre il file in modalità wb e quindi scrive tutto come byte.

Se invece ho aperto il file con 'w', ottengo il secondo errore:

In [403]: x=np.ones((3,3),dtype=np.float64) 
In [404]: with open('test.txt','w') as f: 
    np.savetxt(f,x,fmt='%.5f') 
    .....:  
TypeError: must be str, not bytes 

Ma non c'è nessun problema con

In [405]: with open('test.txt','wb') as f: 
    np.savetxt(f,x,fmt='%.5f') 
    .....:  
In [406]: cat test.txt 
1.00000 1.00000 1.00000 
1.00000 1.00000 1.00000 
1.00000 1.00000 1.00000 

Questo è il Py3.4; Non ho installato numpy con il mio 3.5 Python. Ma non mi aspetterei una differenza.

Does

'%.5f'%1.2342 

lavoro sul vostro sistema? Potresti anche provare

'%.5f %.5f %.5f'%tuple(mat[0,:]) 
+1

Grazie! Ha funzionato! Scrivo anche del testo in questo file, quindi prima ho dovuto aprirlo con "w", quindi riaprirlo con "ab". –

+1

È possibile creare stringhe di byte con "b'one due tre". – hpaulj

+0

Ho avuto lo stesso errore durante la scrittura su un oggetto 'io.StringIO'. In tal caso la soluzione è sostituirla con un oggetto 'io.BytesIO'. – SiggyF