我试图创建hdf 5文件,但输出文件是空的。
我写了一个Python代码,它应该在循环中运行,并在创建的数据集中写入字符串。在文件被保存后,我发现输出文件总是空的。
下面是我写的代码:
h5_file_name = 'sample.h5'
hf = h5py.File(h5_file_name, 'w')
g1 = hf.create_group('Objects')
dt = h5py.special_dtype(vlen=str)
d1 = g1.create_dataset('D1', (2, 10), dtype=dt)
d2 = g1.create_dataset('D2', (3, 10), dtype=dt)
for i in range(10):
d1[0][i] = 'Sample'
d1[1][i] = str(i)
d2[0][i] = 'Hello'
d2[1][i] = 'World'
d2[2][i] = str(i)
hf.close()
如上所述,输出文件为空。
有没有人能指出我在这里错过了什么,提前感谢!
2条答案
按热度按时间zlwx9yxi1#
你的代码为我工作(在ipython会话中):
这将运行并创建一个文件。它不是正常意义上的“空”。但是如果你说的文件是空的意思是它没有把单词写到文件里?所有这些都是原始的
''
。===
问题不在于文件设置,而在于如何设置元素:
使用
tuple
索引样式:对于numpy数组,
d1[0][0]=...
可以工作,但这是因为d1[0]
是d1
的view
,但h5py
(显然)并不完全复制这一点。d1[0]
是一个副本,一个实际的numpy数组,而不是数据集本身。整个数组索引的变体:
使用索引替换类型更改:
d1[0][0]='foobar'
会改变d1[0]
数组,而不会影响d1
数据集。eaf3rand2#
不知道如何使用h5py解决这个问题,但如果你没有绑定到特定的库,看看HDFql,因为它很容易处理HDF5文件。
在Python中使用HDFql,您的用例可以在hyperlabs的帮助下解决,如下所示:
有关如何使用HDFql的其他示例可以在here中找到。