将值从一个 h5py 文件转移到另一个文件

问题描述 投票:0回答:1

在以各种方式为 h5py 组分配值时,我在网上找到了一种语法的描述,我试图为此目的进行调整,但到目前为止还没有奏效,任何帮助将不胜感激。我要在其间传输的两个文件具有相同的组和子组结构。

这是我玩过的语法结构:

import h5py 
f1 = h5py.File('file1.h5','a')
f2 = h5py.File('file2.h5','r')
f1['group1']['subgroup1'] = f2['group1']['subgroup1']  
f1['group2']['subgroup2'] = 1 
f1['group3']['subgroup3'] = array 
f1.close()
f2.close()

我试图将 file2 的 subgroup1 中的值分配给 file1 中的同名子组,它是空的。然后我想在subgroup2中指定一个标量作为唯一的值,然后将一个数组的值赋给subgroup3。我错过了什么?

虽然@Bryce 建议的修复适用于我预先避免的特定示例(谢谢),但我要使用的应用程序仍然无法正常工作:

import h5py 
template = 'dump.h5'   #the template file in the same directory as the notebook
filename =  'dem1.h5'  #name of the file to be created
f1 = File_key_structure(filename,template) #creates an empty file filename with identical structure to a hardcoded template
ftemp = h5py.File(template,'r') 
Display_structure(template,'extras',1)  #lists the group keys of template as well as the subgroups of 'extras
Display_structure(filename,'extras',1)   #lists the group keys of filename as well as the subgroups of 'extras'  

第一行输出模板结构,第二行输出文件名结构:

['dt', 'dump_cadence', 'extras', 'full_dump_cadence', 'gamma', 'header', 'is_full_dump', 'jcon', 'n_dump', 'n_step', 'prims', 't']
<HDF5 group "/extras" (4 members)>
['divB' 'fail' 'fixup' 'git_version']
['dt', 'dump_cadence', 'extras', 'full_dump_cadence', 'gamma', 'header', 'is_full_dump', 'jcon', 'n_dump', 'n_step', 'prims', 't']
<HDF5 group "/extras" (4 members)>
['divB' 'fail' 'fixup' 'git_version']
Out: <HDF5 group "/extras" (4 members)>

我也仔细检查了所有其他组,我得到的每种作业类型的具体错误是:

f1 = h5py.File(filename,'a')
f1['header']['prims'] = np.array([1, 2, 3, 4, 5])  #this works 
f1['extras']['fixup'] = ftemp['extras']['fixup']
f1['dt'] = 1

最后两个赋值给出如下错误:

OSError: Unable to create link (name already exists)

python arrays h5py
1个回答
0
投票

我用我创建的一些随机文件运行你的代码没有问题,所以我猜问题是因为你正在为不存在的文件赋值。

所以我修改了您的代码以在

subgroup1
中创建
file1
如果它不存在,然后将值分配给
subgroups
.

import h5py 
import numpy as np

f1 = h5py.File('file1.h5', 'a')
f2 = h5py.File('file2.h5', 'r')

if 'subgroup1' not in f1['group1']:
    f1['group1'].create_group('subgroup1')

f1['group1']['subgroup1'] = f2['group1']['subgroup1']
f1['group2']['subgroup2'] = 1 
f1['group3']['subgroup3'] = np.array([1, 2, 3])

f1.close()
f2.close()
© www.soinside.com 2019 - 2024. All rights reserved.