python - 在 for 循环中将数据集写入 .hdf5 文件时出现问题

标签 python file h5py

我正在迭代多个文件并读出我想要的信息,这些信息存储在一个 numpy 数组中,然后我将其写入具有唯一名称的 h5py 文件对象(例如,outputdataset_1、outputdataset_2 ......) ,但是当脚本运行时,它仅将最终数据集写入文件 (outputdataset_numFiles)。

为了简单起见,所有的文件解析都被抽象成一个if循环和函数“get_data”,公平有效地假设当代码到达文件末尾时,pts数据结构包含所有正确的值。

for num in range(1,numFiles):
    with h5py.File("outputFileName.hdf5", "w") as f:
        with open("fileAddress" +str(num)) as file:
                lineNum = 0
                while True:
                    line = file.readline(lineNum)
                    if not line and lineNum != 0:
                        s = 'outputdataset_' +str(num)
                        dset = f.create_dataset(s,pts.shape,data=pts)
                        break;
                    if line == criteria:
                        pts = get_data(pts,line)
                    lineNum += 1

最佳答案

问题在于 for num in range(…)with h5py.File(…) 行的顺序;按照您编写的方式,每次加载新文件时都会关闭该文件,并且由于 h5py.File() 是通过模式 'w' 调用的,它将(正确地)覆盖每个循环中的“outputfilename.hdf5”

解决方案:只需交换这些行即可。

或者(但这可能需要更多代码!)您可以使用“追加”文件模式,即 with h5py.File("outputFileName.hdf5", "a") as f — 但是那么如果您多次(迭代)运行该脚本,您可能会遇到 RuntimeError: 'Unable to create link (name haslaished)'。当然,您可以编写额外的代码来检查 hdf5 文件中预先存在的路径并实现某种更新/替换逻辑,但这可能需要一些时间编码。

关于python - 在 for 循环中将数据集写入 .hdf5 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160890/

相关文章:

python - 您可以使用闭包优化函数中的导入吗?

objective-c - 在 iOS 中读取文件时出现 malloc 错误

python - 读取h5数据集python的一部分

python - 如何使用 Python 和 h5py 读取 HDF5 属性(元数据)

python - Tensorboard 类型错误 : __init__() got an unexpected keyword argument 'file'

python - newrelic 和 zope 出错

python - 无法按分类列过滤 pandas 数据框

.net - 智能文件复制算法(与OS无关)

android - 使用字符串删除SD卡android中的文件

conda - 在 conda 上导入 h5/h5py 时出错 : undefined symbol: H5Pget_fapl_direct