numpy.savetxt resulting a formatting mismatch error in python 3.5

后端 未结 1 1828
清歌不尽
清歌不尽 2020-12-05 23:35

I\'m trying to save a numpy matrix (Nx3, float64) into a txt file using numpy.savetxt:

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

Th

相关标签:
1条回答
  • 2020-12-06 00:02

    savetxt opens the file in wb mode, and thus writes everything as bytes.

    If instead I open the file with 'w', I get your second error:

    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
    

    But there's no problem with

    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
    

    This is on Py3.4; I don't have numpy installed with my 3.5 Python. But I wouldn't expect a difference.

    Does

    '%.5f'%1.2342
    

    work on your system? You could also try

    '%.5f %.5f %.5f'%tuple(mat[0,:])
    
    0 讨论(0)
提交回复
热议问题