2017-07-19 127 views
0

我想要写入两个单独的二进制文件(即,满足条件的行的n/2个必须到达文件,并且必须将该矩阵的大小设为(n*n)留给另一个)。我写的如下面的代码:向二进制文件写入列表时出现

def write_to_binary_file(X, y): 
    posiResponse = [] 
    negaResponse = [] 
    for idx, res in enumerate(y): 
     if res == 1: 
      posiResponse.extend(X[idx]) 
     else: 
      negaResponse.extend(X[idx]) 

    with open("POS.bin", mode='wb') as file1: 
     file1.write(bytearray(posiResponse)) 
    file1.close() 
    with open("NEG.bin", mode='wb') as file2: 
     file2.write(bytearray(negaResponse)) 
    file2.close() 

我得到的抱怨阵列和如何我用bytearray()但我不知道如何调整它的错误:

Traceback (most recent call last): 
    File "exper.py", line 173, in <module> 
    write_data(X, y) 
    File "exper.py.py", line 47, in write_data 
    file1.write(bytearray(posiResponse)) 
TypeError: an integer or string of size 1 is required 

请,可有人提供了一个很好的修复谢谢。

+0

你想写一个numpy的阵列到一个二进制文件?你关心它是如何完成的? –

回答

1

posiResponsenegaResponse是列表。 Numpy有一些方法可以让你轻松地写入文件。下面是使用np.ndarray.tofile一个办法:

def write_to_binary_file(X, y): 
    ... # populate posiResponse and negaResponse here 

    np.array(posiResponse).tofile('POS.bin') 
    np.array(negaResponse).tofile('NEG.bin') 

或者,您可以保留这些数据结构的列表,然后使用pickle.dumppickle模块来转储你的数据:

import pickle 
def write_to_binary_file(X, y): 
    ... # populate posiResponse and negaResponse here 

    pickle.dump(posiResponse, open('POS.bin', 'wb')) 
    pickle.dump(negaResponse, open('NEG.bin', 'wb')) 
+1

非常感谢。 – Medo

0

或者改为@ COLDSPEED的回答你可以使用numpy.save

def write_to_binary_file(X, y): 
    posiResponse = [] 
    negaResponse = [] 
    for idx, res in enumerate(y): 
     if res == 1: 
      posiResponse.extend(X[idx]) 
     else: 
      negaResponse.extend(X[idx]) 
    np.save('POS', posiResponse) 
    np.save('NEG', negaResponse) 

不幸的是,它会添加扩展名npy

之后,你可以加载列表回为:

posiResponse = np.load('POS.npy').tolist()