我想将一个数组存储到文件中,并在标题中包含一些额外信息。我想使用 numpy 二进制“.npy”格式。我可以通过首先查找数组部分的开头来从带有额外 header 的 .npy 文件中读取数组吗?
我想做这样的事情。如果 a 的 header 为“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)
最佳答案
当然,您可以将元数据放入文件头。但它有点复杂,除非文件格式已经有元数据的标题(这里似乎是这种情况,除非你可以将它粘贴到描述字段中。npy 似乎有),这意味着你实际上不是使用 .npy 格式,但您自己的格式只有您可以阅读。
考虑将元数据保存在具有相同文件名但以 .meta 结尾的文件中。要么
foobar.npy
foobar.meta
或
foobar.npy
foobar.npy.meta
这样可以大大简化文件格式和文件处理。
关于python - 我可以使用 seek 将额外的 header 信息添加到 numpy .npy 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4620712/