将字符串添加到h5文件

时间:2016-06-06 16:08:24

标签: python string numpy pytables

我有以下代码:

import tables
import numpy as np

filename = "file.h5"

x = np.random.random(150)
z = np.random.random(150)
mystr = " " * 160

f = tables.open_file(filename, mode="w")
hds = f.create_carray(f.root, "x", obj=x, 
                      filters=tables.Filters(complevel=5, complib='zlib'))
hds = f.create_carray(f.root, "z", obj=z, 
                      filters=tables.Filters(complevel=5, complib='zlib'))                
f.close()

我想在我的文件中添加一个长度为160的字符串。有一种优雅的方法吗?

提前谢谢你。

2 个答案:

答案 0 :(得分:2)

使用h5py,您可以将包含字符串(或仅一个)的numpy数组存储为数据集。或者,您可以将字符串存储为组或数据集的属性。

 http://docs.h5py.org/en/latest/strings.html

可以这么简单:

dset.attrs["title"] = "Hello"

我还没有使用tables,但它也必须能够访问这些属性。在文档中是不是有什么东西?

文件对象本身也有一个.attrs字典。

答案 1 :(得分:0)

在H5中存储字符串类型数据有些棘手。这是首次使用Python的H5用户的常见问题。在将数据类型放入H5数据集之前(即,它是字符串,整数还是浮点数),必须清楚地显示数据类型。对于字符串数据类型,您需要将其指定为变量。例如, dt = h5py.string_dtype()

下面是将字符串放入H5文件的示例。

import h5py
data = 'value in string'
f= h5py.File('./fname.h5','w')
try:
    dt = h5py.string_dtype()
    f.create_dataset('str_data', data=data, dtype=dt)
except Exception as ex:
    print(ex)
finally:
    f.close()

此外,请使用以下代码检查数据是否正确存储,以供参考。

f= h5py.File('./fname.h5','r')
try:
    print(f.keys())
    print(f['str_data'][()])
except Exception as ex:
    print(ex)
finally:
    f.close()

有关更多参考,请阅读有关HDF5中String的H5文档。 http://docs.h5py.org/en/stable/strings.html