您需要的是文件中所有数据集的列表。我认为这里需要的是recursive function的概念。这将允许您从一个组中提取所有的“数据集”,但是当其中一个看起来是组本身时,递归地执行相同的操作,直到找到所有数据集为止。例如:/
|- dataset1
|- group1
|- dataset2
|- dataset3
|- dataset4
伪代码中的函数应该如下所示:
^{pr2}$
例如:/dataset1是一个数据集:将路径添加到输出,给出out = ['/dataset1']
/group不是数据集:调用getdatasets('/group',file)/group/dataset2是一个数据集:将路径添加到输出,给出nested_out = ['/group/dataset2']
/group/dataset3是一个数据集:将路径添加到输出,给出nested_out = ['/group/dataset2', '/group/dataset3']
这是我们已经拥有的:out = ['/dataset1', '/group/dataset2', '/group/dataset3']
/dataset4是一个数据集:将路径添加到输出,给出out = ['/dataset1', '/group/dataset2', '/group/dataset3', '/dataset4']
此列表可用于将所有数据复制到另一个文件中。在
要制作一个简单的克隆,可以执行以下操作。在import h5py
import numpy as np
# function to return a list of paths to each dataset
def getdatasets(key,archive):
if key[-1] != '/': key += '/'
out = []
for name in archive[key]:
path = key + name
if isinstance(archive[path], h5py.Dataset):
out += [path]
else:
out += getdatasets(path,archive)
return out
# open HDF5-files
data = h5py.File('old.hdf5','r')
new_data = h5py.File('new.hdf5','w')
# read as much datasets as possible from the old HDF5-file
datasets = getdatasets('/',data)
# get the group-names from the lists of datasets
groups = list(set([i[::-1].split('/',1)[1][::-1] for i in datasets]))
groups = [i for i in groups if len(i)>0]
# sort groups based on depth
idx = np.argsort(np.array([len(i.split('/')) for i in groups]))
groups = [groups[i] for i in idx]
# create all groups that contain dataset that will be copied
for group in groups:
new_data.create_group(group)
# copy datasets
for path in datasets:
# - get group name
group = path[::-1].split('/',1)[1][::-1]
# - minimum group name
if len(group) == 0: group = '/'
# - copy data
data.copy(path, new_data[group])
当然,进一步的定制是可能的,这取决于您想要什么。你描述了一些文件的组合。那样的话你就得new_data = h5py.File('new.hdf5','a')
可能会给这条路加些什么。在