1、關於安裝:
如果你使用的是Anaconda的話,安裝命令如下:
conda install h5py
如果沒有,安裝命令如下:
pip install h5py
2、核心概念
讀取HDF5文件,假如現有一個HDF5文件test.hdf5
>>> import h5py >>> f = h5py.File("test.hdf5", "r")
第一行導入h5py模塊,第二行讀取文件為File object。對File object操作就行Python的字典相似;
>>> list(f.keys())
['mydataset']
這樣我們可以查看key,就像字典一樣。經查看里面有一個數據“mydataset”,我們可以提取該數據;
>>> dset = f["mydataset"]
讀取出來的數據更像是Python中的Numpy arrays對象;
>>> dset.shape (100,) >>> dset.dtype dtype('int32')
支持數組的切片;
>>> dset[...] = np.arange(100) >>> dset[0] 0 >>> dset[10] 10 >>> dset[1:100:10] array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
3、創建一個文件和數據
>>> import h5py >>> import numpy as np >>> f = h5py.File("mytestfile.hdf5", "w")
>>> dset = f.create_dataset("mydataset", (100,), dtype='i')
4、組和層級組織
>>> dset.name u'/mydataset'
The "folders" in this system are called groups, The File object we create is itself a group, in this case the root group ,name /
>>> f.name u'/'
當然也可以創建子組;
>>> dset2 = h5py.File('mydataset..hdf5', 'a') >>> grp = f.create_group("subgroup")
>>> dset2 = grp.create_dataset('another_dataset", (50,), dtype='f')
>>> dset2.name
u'/subgroup/another_dataset'
可以直接指定路徑創建;
>>> dset3 = f.create_dataset('subgroup2/dataset_three', (10,), dtype='i') >>> dset3.name u'/subgroup2/dataset_three'