python3-numpy:使用 numpy savetxt 附加到文件 [英] python3-numpy: Appending to a file using numpy savetxt
问题描述
我正在尝试使用 numpy 的 savetxt 函数将数据附加到文件中.下面是最小的工作示例
I am trying to append data to a file using numpy's savetxt function. Below is the minimum working example
#!/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()
我得到的错误与错误类型有关
The error that I got is something about the type of the error
文件/usr/lib/python3/dist-packages/numpy/lib/npyio.py",第1073行,在保存文件中fh.write(asbytes(format % tuple(row) + newline)) TypeError: must be str, not bytes
File "/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 bytes
python2 中不会发生此错误,所以我想知道可能是什么问题.谁能帮帮我?
This error doesn't occur in python2 so I am wondering what the issue could be. Can anyone help me out?
推荐答案
你应该以二进制方式打开文件.
You should open file by binary mode.
#!/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文件?
reference: python - How to write a numpy array to a csv file? - Stack Overflow How to write a numpy array to a csv file?
这篇关于python3-numpy:使用 numpy savetxt 附加到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!