Python 向h5文件添加字符串
我有以下代码:Python 向h5文件添加字符串,python,string,numpy,pytables,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=t
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的字符串。有没有一种优雅的方法可以做到这一点
先谢谢你 使用
h5py
可以将包含字符串(或仅一个)的numpy数组存储为数据集。或者,可以将字符串存储为组或数据集的属性
http://docs.h5py.org/en/latest/strings.html
它可以简单到:
dset.attrs["title"] = "Hello"
我没有使用表
,但它也必须能够访问这些属性。文档中没有什么东西吗
file对象本身也有一个
.attrs
字典。在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中字符串的H5文档。