我想在循环期间为追加 numpy数组创建两个二进制文件到每个文件中。我编写了以下方法(我使用Python 2.7):
for _ in range(5):
C = np.random.rand(1, 5)
r = np.random.rand(1, 5)
with open("C.bin", "ab") as file1, open("r.bin", "ab") as file2:
# Append to binary files
np.array(C).tofile(file1)
np.array(r).tofile(file2)
# Now printing to check if appending is successful
C = np.load("C.bin")
r = np.load("r.bin")
print (C)
print (r)
但是,我一直收到这个错误:
Traceback (most recent call last):
File "test.py", line 15, in <module>
C = np.load("C.bin")
File "/anaconda/lib/python2.7/site-packages/numpy/lib/npyio.py", line 429, in load
"Failed to interpret file %s as a pickle" % repr(file))
IOError: Failed to interpret file 'C.bin' as a pickle
我试图解决它,但我看不到更多。任何帮助表示赞赏。
注意:我有意使用np.load
,因为稍后我会将数据集从磁盘加载到numpy数组中以便进一步处理。
答案 0 :(得分:1)
您应该使用numpy中构建的save
方法将数组存储在文件中。这是您的代码应该是什么样的:
for _ in range(5):
C = np.random.rand(1, 5)
r = np.random.rand(1, 5)
np.save('C', C)
np.save('r', r)
# Now printing to check if appending is successful
C = np.load("C.npy")
r = np.load("r.npy")
print (C)
print (r)
del C, r
请参阅文档https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.load.html