![](/img/trans.png)
[英]Writing a string to a text file and then an array using numpy savetxt
[英]python3-numpy: Appending to a file using numpy savetxt
我正在尝试使用 numpy 的 savetxt 函数将数据附加到文件中。 下面是最小的工作示例
#!/usr/bin/env python3
import numpy as np
f=open('asd.dat','a')
for iind in range(4):
a=np.random.rand(10,10)
np.savetxt(f,a)
f.close()
我得到的错误是关于错误类型的
文件 "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 1073, in savetxt fh.write(asbytes(format % tuple(row) + newline)) TypeError: must be str, not字节
这个错误不会发生在 python2 中,所以我想知道可能是什么问题。 谁能帮我吗?
您应该以二进制模式打开文件。
#!/usr/bin/env python3
import numpy as np
f=open('asd.dat','ab')
for iind in range(4):
a=np.random.rand(10,10)
np.savetxt(f,a)
f.close()
参考:python - 如何将 numpy 数组写入 csv 文件? - 堆栈溢出如何将 numpy 数组写入 csv 文件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.