开发者

Can I add extra header information to a numpy .npy file by using seek?

I want to store an array to file with some extra information in 开发者_Go百科a header. I want to use the numpy binary '.npy' format. Can I read an array form a .npy file with an extra header by first seeking to the beginning of the array part?

I want to do something like this. If a have a header that is 'n' bytes:

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)


Sure you can put metadata into a file header. But it is a bit complex, and unless the file format has a header for metadata already (which seems to be the case here, unless you can stick it into the description field .npy seems to have), it means you aren't actually using the .npy format, but your own format only you can read.

Consider saving the metadata in files with the same filename, but a .meta ending. Either

foobar.npy
foobar.meta

or

foobar.npy
foobar.npy.meta

That way you simplify the file format and file handling a lot.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜