I want to create two binary files to append numpy arrays into each one of them during a loop. I wrote the following method (I use Python 2.7):
我想创建两个二进制文件,在循环期间将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)
However, I keep getting this error:
但是,我一直收到这个错误:
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
I tried to fix it but I cannot see anything more. Any help is appreciated.
我试图解决它,但我看不到更多。任何帮助表示赞赏。
NOTE: I intentionally want to use np.load
because later on I will be loading the dataset from the disk into a numpy array for further processing.
注意:我故意想使用np.load,因为稍后我会将数据集从磁盘加载到numpy数组中以便进一步处理。
1 个解决方案
#1
1
You should use the save
method that is built in the numpy to store the array in the files. Here what your code should look like:
您应该使用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
Please refer to the documentation https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.load.html
请参阅文档https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.load.html
#1
1
You should use the save
method that is built in the numpy to store the array in the files. Here what your code should look like:
您应该使用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
Please refer to the documentation https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.load.html
请参阅文档https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.load.html