2011-01-06 72 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 

这样,你简化了文件格式和文件处理很多。

相关问题