【问题标题】:numpy.savetxt resulting a formatting mismatch error in python 3.5numpy.savetxt 在 python 3.5 中导致格式不匹配错误
【发布时间】:2016-05-24 04:57:16
【问题描述】:

我正在尝试使用 numpy.savetxt 将 numpy 矩阵(Nx3,float64)保存到 txt 文件中:

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

此行在 python 2.7 中有效,但在 python 3.5 中,我收到以下错误:

TypeError: 数组 dtype ('float64') 和格式不匹配 说明符('%.5f %.5f %.5f')

当我步入 savetxt 代码时,在 catch 块(numpy.lib.npyio,第 1158 行)中打印错误(traceback.format_exc()),错误完全不同:

TypeError: write() 参数必须是 str,而不是字节

导致异常的代码行如下:

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

我试图删除 asbytes,它似乎修复了这个错误。它是numpy中的错误吗?

【问题讨论】:

    标签: numpy formatting python-3.5


    【解决方案1】:

    savetxtwb 模式打开文件,因此将所有内容写入字节。

    如果我用“w”打开文件,我会收到第二个错误:

    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
    

    但是没有问题

    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
    

    这是在 Py3.4 上的;我的 3.5 Python 没有安装 numpy。但我不希望有什么不同。

    '%.5f'%1.2342
    

    在您的系统上工作?你也可以试试

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

    【讨论】:

    • 谢谢!有效!我也在给这个文件写文本,所以首先我需要用'w'打开它,然后用'ab'重新打开它。
    • 你可以用b'one two three'创建字节串。
    • 我在写入 io.StringIO 对象时遇到了同样的错误。在这种情况下,解决方案是将其替换为 io.BytesIO 对象。
    • 哇,这有助于解决我遇到的另一个问题,尽管我正在附加一个文件 file=open(file, 'ab') mode 并且它适用于 savetext(刚刚添加了 b)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2017-01-08
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多