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行, 在savetxt中 fh.write(asbytes(format%tuple(row)+ newline))TypeError:必须为str,而不是字节
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屋!