2014-07-17 32 views
0

如何將NumPy數組保存爲較大文本文件的一部分?我可以使用savetxt將數組寫入臨時文件,然後將它們讀回到一個字符串中,但這似乎是冗餘且效率低下的編碼(某些數組將很大)。例如:將numpy數組保存爲較大文本文件的一部分

from numpy import * 

a=reshape(arange(12),(3,4)) 
b=reshape(arange(30),(6,5)) 

with open ('d.txt','w') as fh: 
    fh.write('Some text\n') 
    savetxt('tmp.txt', a, delimiter=',') 
    with open ("tmp.txt", "r") as th: 
     str=th.read() 
    fh.write(str) 
    fh.write('Some other text\n') 
    savetxt('tmp.txt', b, delimiter=',') 
    with open ("tmp.txt", "r") as th: 
     str=th.read() 
    fh.write(str) 

回答

2

第一個參數的savetxt

FNAME:文件名或文件處理

所以,你可以在append mode打開文件,並寫入它:

with open ('d.txt','a') as fh: 
    fh.write('Some text\n') 
    savetxt(fh, a, delimiter=',') 
    fh.write('Some other text\n') 
    savetxt(fh, b, delimiter=',') 
+0

謝謝羅馬!當然,我完全錯過了文檔的那一部分。 –