如何在Python中读取HDF5文件 [英] How to read HDF5 files in Python
本文介绍了如何在Python中读取HDF5文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从Python中的hdf5文件读取数据.我可以使用h5py
读取hdf5文件,但无法弄清楚如何访问文件中的数据.
I am trying to read data from hdf5 file in Python. I can read the hdf5 file using h5py
, but I cannot figure out how to access data within the file.
import h5py
import numpy as np
f1 = h5py.File(file_name,'r+')
这有效并且读取了文件.但是,如何访问文件对象f1
中的数据?
This works and the file is read. But how can I access data inside the file object 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文档.
See h5py docs for more information.
- JSON:非常适合编写人类可读的数据;非常常用(读和写)
- CSV:超级简单的格式(读取和写入)
- pickle:一种Python序列化格式(读取和写入)
- MessagePack ( Python软件包):更紧凑的表示形式(读取和写入)
- HDF5 (读取和写入)
- XML:也*叹*(阅读&
- JSON: Nice for writing human-readable data; VERY commonly used (read & write)
- CSV: Super simple format (read & write)
- pickle: A Python serialization format (read & write)
- MessagePack (Python package): More compact representation (read & write)
- HDF5 (Python package): Nice for matrices (read & write)
- XML: exists too *sigh* (read & write)
对于您的应用程序,以下内容可能很重要:
For your application, the following might be important:
- 其他编程语言的支持
- 阅读/写作表现
- 紧凑性(文件大小)
另请参阅:数据序列化格式的比较
如果您想寻找一种制作配置文件的方法,则可能需要阅读我的短文 Python中的配置文件
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
这篇关于如何在Python中读取HDF5文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文