向h5文件追加数据

该代码示例展示了如何使用h5py库在Python中向H5文件追加数据。首先生成随机特征矩阵,然后定义一个函数write_h5用于将数据写入或追加到H5文件。通过循环将每一层特征写入文件,并用文件名作为数据集的键。最后,打开文件读取并打印所有数据集的内容。
摘要由CSDN通过智能技术生成

向h5文件追加数据

import h5py
import numpy as np
import os

features = np.random.randn(3,3,3)
print(features)
result_path = "train_feature.h5"
def write_h5(feature,name):
    if not os.path.exists(result_path):
        # a 是追加, r是只读, w是写
        file = h5py.File(result_path, "a")
    else:
        file = h5py.File(result_path, 'a')

    file.create_dataset(name=name, data=feature)
    file.close()

for i in range(0,3):
    feat = features[i,:,:]
    name = str(i)
    write_h5(feat, name)

with h5py.File(result_path, 'r') as hf:
    for key in hf.keys():
        print(hf[key].name)  # 获得名称,相当于字典中的key
    for idx in range(0, 3):
        print(hf[str(idx)][:])
    hf.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值