示例:
#encoding=utf-8
import h5py
import os
#要写入的数据
a1 = [[11, 12], [13, 17], [14, 15]]
b1 = [[145, 191, 113], [144, 167, 129]]
a2 = [[21, 22], [23, 27], [24, 25]]
b2 = [[245, 291, 213], [244, 267, 229]]
file_name = 'test.h5'
#创建文件并写入数据
if not os.path.exists(file_name):
f = h5py.File(file_name, 'w')
else:
f = h5py.File(file_name, 'a')
f.create_dataset('a1', data=a1)
f.create_dataset('b1', data=b1)
f.close()
#追加数据
if not os.path.exists(file_name):
f = h5py.File(file_name, 'w')
else:
f = h5py.File(file_name, 'a')
f.create_dataset('a2', data=a2)
f.create_dataset('b2', data=b2)
f.close()
#追加数据
if not os.path.exists(file_name):
f = h5py.File(file_name, 'w')
else:
f = h5py.File(file_name, 'a')
f.create_dataset('a3', data='this is a3')
f.close()
#读取并输出
f = h5py.File('test.h5', 'r')
print('--iterms: ', len(f.keys()))
a_1 = f['a1']
b_1 = f['b1']
a_2 = f['a2']
b_2 = f['b2']
print(a_1[:], '\n')
print(b_1[:], '\n')
print(a_2[:], '\n')
print(b_2[:], '\n')
print(f['a3'].value, '\n')
f.close()