2017-12-03 33 views
0

我正在嘗試將list寫入二進制文件並稍後再次加載它。我有這個代碼:將列表寫入二進制文件時的問題

with open('W.bin', mode='wb') as file:         
    file.write(bytearray(model.estimator.intercepts_)) 
file.close() 

其中model.estimator.intercepts_是一個列表。然而,我得到這個錯誤:

File "LM.py", line 200, in model_training 
    file.write(bytearray(model.estimator.intercepts_)) 
TypeError: an integer or string of size 1 is required 

我不知道我的代碼有什麼問題嗎?謝謝

+2

你有你想要寫 –

+0

什麼是你的列表中的內容爲空值? –

回答

0

這裏有兩件事出錯了。

首先,您的列表必須僅包含字符(大小爲1的字符串)或範圍在0到256之間的整數以使用bytearray。列表中的某些元素不能滿足要求,並且您得到TypeError

其次,你只能寫一個字符串到一個文件。如果你需要寫任何東西,你應該使用pickle

import pickle 

with open('W.bin', mode='w') as file:         
    pickle.dump(your_array), file) 

,然後讀做

with open('W.bin', mode='r') as file:         
    your_array = pickle.load(file) 
+0

我可以有這個小問題。 'mode ='w''將**覆蓋**現有文件,對嗎? – David

+0

它的確如此,你可以在這裏閱讀關於打開的不同模式:https://docs.python.org/2/library/functions.html#open 雖然如果你使用pickle,那麼追加它就沒有意義了到文件。 –