2011-01-06 69 views
2

我想存儲一個數組,以在頭文件中添加一些額外的信息。我想使用numpy二進制'.npy'格式。我可以通過首先尋找數組部分的開頭來讀取帶有額外標頭的.npy文件的數組嗎?我可以通過使用seek向numpy的.npy文件添加額外的頭信息嗎?

我想做這樣的事情。如果一個標頭是'n'字節:

from tempfile import TemporaryFile 
outfile = TemporaryFile() 
# Write header to first 'n' bytes. 
... 
# Write the array after the header. 
outfile.seek(n) 
x = np.arange(10) 
np.save(outfile, x) 

# Then to read it back in: 
outfile.seek(0) 
# Read the header. 
... 
# Read the array. 
outfile.seek(n) 
y = np.load(outfile) 

回答

1

當然你可以把元數據放到文件頭中。但它有點複雜,除非文件格式已經有元數據頭(這裏似乎是這種情況,除非你可以將它粘貼到描述字段中.npy似乎有),這意味着你實際上並不是使用.npy格式,但只有您自己的格式可以閱讀。

考慮將元數據保存在具有相同文件名的文件中,但以.meta結尾。無論是

foobar.npy 
foobar.meta 

foobar.npy 
foobar.npy.meta 

這樣,你簡化了文件格式和文件處理很多。

相關問題