簡體   English   中英

如何使用 H5py 在 python 3 中正確打開、讀取和保存到單個文件

[英]How to properly open, read from and save to a single file in python 3 using H5py

我是 Python 和通用編程的新手,可能犯了可怕的錯誤。 感謝您的任何幫助。 我想通過加載其他人准備的一些 hdf5 數據或加載我自己的 hdf5 文件來初始化我的類的成員。 我試過這個:

import numpy as np
import h5py
import sys

class ashot:
    def __init__(self, path, load=False):
        if load is False:
            self.name = "_".join(re.findall(r"(\d+)_(\d+)/aa/shot_(\d+)", path)[0])
            f = h5py.File(path, "r")
            numpyarray = f["data/data"]
            self.array = numpyarray
        else:
            f = h5py.File(path, "a")
            self.array = f["array"]
            self.name = f["array"].attrs["name"]

    def saveshot(self):
        s = h5py.File(self.name+".h5", "a")
        s.create_dataset("array", data=self.array)
        s["array"].attrs["name"] = self.name
        s.close()
        return()

但是如果我使用以下方法運行它:

testshot = ashot("somepath to data storage")
testshot.saveshot()
loadshot = ashot("the path I stored the shot testshot", load = True)
loadshot.saveshot()

我得到

Traceback (most recent call last):
File "program path.py", line 191, in <module>
loadshot.saveshot()
File "program path.py", line 114, in saveshot
s.create_dataset("array", data=self.array)
File "C:\Users\Drossel\AppData\Local\Programs\Python\Python36\lib\site-packages\h5py\_hl\group.py", line 109, in create_dataset
self[name] = dset
File "C:\Users\Drossel\AppData\Local\Programs\Python\Python36\lib\site-packages\h5py\_hl\group.py", line 277, in __setitem__
h5o.link(obj.id, self.id, name, lcpl=lcpl, lapl=self._lapl
File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py\h5o.pyx", line 202, in h5py.h5o.link
RuntimeError: Unable to create link (name already exists)

我有點明白我正在嘗試寫入一個已經打開的文件,但是由於某種原因使用 numpy.save 和 numpy.load 的相同代碼有效。 我嘗試在 assiningthe self.array 后關閉文件,但后來我得到了

NameError: name 'ashot' is not defined

因為,我假設, f 那時只是一個文件句柄。 我究竟做錯了什么?

不允許創建兩次數據集:

In [34]: F = h5py.File('testh546643026.h5','a')
In [35]: ds = F.create_dataset('tst',data=np.arange(3))
In [36]: F.close()
In [37]: F = h5py.File('testh546643026.h5','a')
In [38]: ds = F.create_dataset('tst',data=np.arange(3))
....
RuntimeError: Unable to create link (Name already exists)

require可以獲取現有數據集(或創建一個新數據集),但 shape 和 dtype 必須匹配(請參閱其文檔):

In [41]: ds = F.require_dataset('tst',(3,),int)
In [42]: ds
Out[42]: <HDF5 dataset "tst": shape (3,), type "<i4">
In [43]: ds.value
Out[43]: array([0, 1, 2])
In [44]: ds[:]=np.ones((3,))
In [45]: ds.value
Out[45]: array([1, 1, 1])

如果要自由替換現有數據集,則必須先將其刪除。

如何使用 h5py 編輯 h5 文件?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM