2014-03-27 11 views
0

從Python腳本中,我需要在文本文件中寫入兩個浮點矩陣,並在第二個Python腳本中再次讀取文本文件。所以我試過這樣:嘗試在文本文件中編寫和讀取兩個矩陣

#ElR is the first matrix and ShR is the second matrix 
with open("house.txt", "w") as fE: 
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ElR) 

with open("house.txt", "w") as fS: 
    fS.writelines(','.join(str(j) for j in i) + '\n' for i in ShR) 

但是,這樣做只在文本文件中寫入ShR的值而不是ElR的值。它有什麼不對? 此外,有沒有辦法讀取文本文件並將兩個矩陣保存在其他矩陣中?所需的腳本會是這個樣子(我猜):

r_file = open("house.txt", "r") 
new_ElR = r_file.readline() 
new_ShR = r_file.readline() 
r_file.close() 

回答

3

您需要打開文件與append模式。

#ElR is the first matrix and ShR is the second matrix 
with open("house.txt", "w") as fE: 
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ElR) 

with open("house.txt", "a") as fS: # <-- notice the a 
    fS.writelines(','.join(str(j) for j in i) + '\n' for i in ShR) 

現在您將覆蓋第二個with -block中的文件。使用上述解決方案,您將覆蓋第一個文件中的現有文件,並在第二個文件中附加該文件。

或者正如評論中提到的這個答案,你可以一口氣寫完。

#ElR is the first matrix and ShR is the second matrix 
with open("house.txt", "w") as fE: 
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ElR) 
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ShR) 

您可以縮短這通過連接列表..

with open("house.txt", "w") as fE: 
    fE.writelines(','.join(str(j) for j in i) + "\n" for i in ElR + ShR) 

如果矩陣不需要是人類可讀的,我會用pickle它們序列化,並避免重新創建它們。喜歡的東西:

>>> import pickle 
>>> with open("my_matrices.pkl", "wb") as f: 
... pickle.dump(my_matrix_object, f) 
... 

而當你需要他們..

>>> with open("my_matrices.pkl", "rb") as f: 
... matrix = pickle.load(f) 
... 
+1

或OP可以只使用一個'開放的()'和一次性寫... –

+0

@ m.wasowski是啊,我會補充一點。 – msvalkon

+1

使用'pickle'的解決方案對我的目的更好。所以我做了它,它的工作原理。非常感謝你們! –

相關問題