gpt4 book ai didi

python-3.x - python3-numpy : Appending to a file using numpy savetxt

转载 作者:行者123 更新时间:2023-12-02 22:27:42 25 4
gpt4 key购买 nike

我正在尝试使用 numpy 的 savetxt 函数将数据 append 到文件中。下面是最小的工作示例

#!/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()

我收到的错误与错误类型有关

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 中不会发生,所以我想知道问题可能是什么。谁能帮帮我吗?

最佳答案

您应该以二进制模式打开文件。

#!/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 文件? - 堆栈溢出How to write a numpy array to a csv file?

关于python-3.x - python3-numpy : Appending to a file using numpy savetxt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com