[英]Can't access returned h5py object instance
我這里有一個很奇怪的問題。 我有 2 個函數:一個讀取使用 h5py 創建的 HDF5 文件,另一個創建一個新的 HDF5 文件,該文件連接前一個 function 返回的內容。
def read_file(filename):
with h5py.File(filename+".hdf5",'r') as hf:
group1 = hf.get('group1')
group1 = hf.get('group2')
dataset1 = hf.get('dataset1')
dataset2 = hf.get('dataset2')
print group1.attrs['w'] # Works here
return dataset1, dataset2, group1, group1
並創建文件 function
def create_chunk(start_index, end_index):
for i in range(start_index, end_index):
if i == start_index:
mergedhf = h5py.File("output.hdf5",'w')
mergedhf.create_dataset("dataset1",dtype='float64')
mergedhf.create_dataset("dataset2",dtype='float64')
g1 = mergedhf.create_group('group1')
g2 = mergedhf.create_group('group2')
rd1,rd2,rg1,rg2 = read_file(filename)
print rg1.attrs['w'] #gives me <Closed HDF5 group> message
g1.attrs['w'] = "content"
g1.attrs['x'] = "content"
g2.attrs['y'] = "content"
g2.attrs['z'] = "content"
print g1.attrs['w'] # Works Here
return mergedhf.get('dataset1'), mergedhf.get('dataset2'), g1, g2
def calling_function():
wd1, wd2, wg1, wg2 = create_chunk(start_index, end_index)
print wg1.attrs['w'] #Works here as well
現在的問題是,我可以訪問由 wd1、wd2、wg1 和 wg2 創建和表示的新文件中的數據集和屬性,我可以訪問屬性數據,但我無法執行我已閱讀並返回的內容的價值。
當我返回對調用 function 的引用時,任何人都可以幫我獲取數據集和組的值嗎?
問題出在read_file
中,這一行:
with h5py.File(filename+".hdf5",'r') as hf:
這將在with
塊的末尾關閉hf
,即當read_file
返回時。 發生這種情況時,數據集和組也會關閉,您將無法再訪問它們。
有(至少)兩種方法可以解決這個問題。 首先,您可以像在create_chunk
中一樣打開文件:
hf = h5py.File(filename+".hdf5", 'r')
並在關閉它之前保留對hf
的引用,只要你需要它:
hf.close()
另一種方法是從read_file
中的數據集中復制數據並返回這些數據:
dataset1 = hf.get('dataset1')[:]
dataset2 = hf.get('dataset2')[:]
請注意,您不能對組執行此操作。 只要您需要對組執行操作,文件就需要打開。
問題出在 read_file 中,這一行:
with h5py.File(filename+".hdf5",'r') as hf:
這會在 with 塊的末尾關閉 hf,即當 read_file 返回時。 發生這種情況時,數據集和組也會關閉,您將無法再訪問它們。
對於那些遇到這種情況並正在閱讀標量數據集的人,請確保使用[()]
進行索引:
scalar_dataset1 = hf['scalar_dataset1'][()]
我遇到了與 OP 類似的問題,導致返回值<closed hdf5 dataset>
。 但是,在嘗試使用[:]
對我的標量數據集進行切片時,我會得到一個ValueError 。
"ValueError: Illegal slicing argument for scalar dataspace"
使用[()]
進行索引以及@Yossarian 的回答有助於解決我的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.