20

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

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

...

我想创建一个新文件,只有:A/B/dataset1,dataset2 A/C/dataset1,dataset2

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

我做了:

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

问题是我得到了dest.h5:

B/dataset1, dataset2

而且我缺少部分树状结构。

4

1 回答 1

32

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']
于 2014-07-02T13:52:48.690 回答