如何使用Python部分地复制一个Hdf5文件到一个新的文件中,并保持相同的结构?

2024-06-16 13:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的hdf5文件,看起来像这样:

A/B/dataset1, dataset2
A/C/dataset1, dataset2
A/D/dataset1, dataset2
A/E/dataset1, dataset2

。。。

我只想创建一个新文件: A/B/数据集1,数据集2 空调/数据集1,数据集2

在python中最简单的方法是什么?

我做到了:

fs = h5py.File('source.h5', 'r')
fd = h5py.File('dest.h5', 'w')
fs.copy('group B', fd)

问题是我得到dest.h5:

B/dataset1, dataset2

我错过了一部分树丛。


Tags: 文件数据方法sourcefsfiledesthdf5
1条回答
网友
1楼 · 发布于 2024-06-16 13:25:57

fs.copy('A/B', fd)不会将路径/A/B/复制到fd,它只复制组B(如您所发现的那样!)。因此,首先需要创建路径的其余部分:

fd.create_group('A')
fs.copy('A/B', fd['/A'])

或者,如果你经常使用这个组:

fd_A = fd.create_group('A')
fs.copy('A/B', fd_A)

这将B组从fs['/A/B']复制到fd['/A']

In [1]: fd['A/B'].keys()
Out[1]: [u'dataset1', u'dataset2']

有一种自动的方法:

# Get the name of the parent for the group we want to copy
group_path = fs['/A/B'].parent.name

# Check that this group exists in the destination file; if it doesn't, create it
# This will create the parents too, if they don't exist
group_id = fd.require_group(group_path)

# Copy fs:/A/B/ to fd:/A/G
fs.copy('/A/B', group_id, name="G")

print(fd['/A/G'].keys())
# [u'dataset1', u'dataset2']

相关问题 更多 >