gpt4 book ai didi

python - 如何在不覆盖的情况下写入hdf5文件?

转载 作者:太空狗 更新时间:2023-10-30 00:13:58 25 4
gpt4 key购买 nike

抱歉,如果这是关于 h5py 的非常基本的问题。

我正在阅读文档,但没有找到类似的示例。

我正在尝试使用 Python 创建多个 hdf5 数据集,但结果是在我关闭文件后数据将被覆盖。

假设我做了以下事情:

import numpy as np
import h5py
f = h5py.File('test.hdf5', 'w')
f.create_dataset('data1', data = np.ones(10))
f.close()
f = h5py.File('test.hdf5', 'w')
f.create_dataset('data0', data = np.zeros(10))
f.close()
f = h5py.File('test.hdf5', 'r')
f["data1"].value
f.close()

我明白了

KeyError: "Unable to open object (Object 'data1' doesn't exist)"

如果我追加数据,这需要首先以 'w' 模式打开,然后以 'a' 模式追加,有两个不同的语句。

import numpy as np
import h5py
f = h5py.File('test.hdf5', 'w')
f.create_dataset('data1', data = np.ones(10))
f.close()
f = h5py.File('test.hdf5', 'a')
f.create_dataset('data0', data = np.zeros(10))
f.close()
f = h5py.File('test.hdf5', 'r')
f["data1"].value
f.close()

如果我在这两种情况下都以 'a' 模式打开文件:

import numpy as np
import h5py
f = h5py.File('test.hdf5', 'a')
f.create_dataset('data1', data = np.ones(10))
f.close()
f = h5py.File('test.hdf5', 'a')
f.create_dataset('data0', data = np.zeros(10))
f.close()
f = h5py.File('test.hdf5', 'r')
print(f['data1'].value)
f.close()

RuntimeError: Unable to create link (Name already exists)

根据文档,数据应该连续存储,但我没有找到如何避免覆盖数据。

如何仅使用一条语句将数据存储在先前关闭的 hdf5 上?

最佳答案

如果你想在每次运行中创建一个唯一的文件,那么你应该考虑这样命名文件,一个例子是将时间戳添加到文件名中,一个非常简单的例子是使用 datetime 模块和nowstrftime 方法来创建文件名。示例 -

import datetime
filename = "test_{}.hdf5".format(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S"))

然后您可以使用该文件名打开该文件。


演示 -

>>> import datetime
>>> filename = "test_{}.hdf5".format(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S"))
>>> filename
'test_2015_08_09_13_33_43.hdf5'

关于python - 如何在不覆盖的情况下写入hdf5文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31901887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com