如何在Python中读取HDF5文件


问题内容

我正在尝试从Python中的hdf5文件读取数据。我可以使用读取hdf5文件h5py,但无法弄清楚如何访问文件中的数据。

我的密码

import h5py    
import numpy as np    
f1 = h5py.File(file_name,'r+')

这可以正常工作并读取文件。但是,如何访问文件对象内部的数据f1


问题答案:

读取HDF5

import h5py
filename = "file.hdf5"

with h5py.File(filename, "r") as f:
    # List all groups
    print("Keys: %s" % f.keys())
    a_group_key = list(f.keys())[0]

    # Get the data
    data = list(f[a_group_key])

写HDF5

import h5py

# Create random data
import numpy as np
data_matrix = np.random.uniform(-1, 1, size=(10, 3))

# Write data to HDF5
with h5py.File("file.hdf5", "w") as data_file:
    data_file.create_dataset("group_name", data=data_matrix)

有关更多信息,请参见h5py docs

备择方案

对于您的应用程序,以下内容可能很重要:

  • 其他编程语言的支持
  • 阅读/写作表现
  • 紧凑度(文件大小)

另请参阅:数据序列化格式的比较

如果您想寻找一种制作配置文件的方法,则可能需要阅读我的短文《Python中的配置文件》。