如何使用pytables取消引用外部链接列表? [英] How to de-reference a list of external links using pytables?

查看:106
本文介绍了如何使用pytables取消引用外部链接列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用pytables创建了从一个hdf5文件到另一个文件的外部链接.我的问题是如何在循环中取消引用它?

I have created external links leading from one hdf5 file to another using pytables. My question is how to de-reference it in a loop?

例如:

假设file_name = "collection.h5",其中存储了外部链接

Let's assume file_name = "collection.h5", where external links are stored

我在根节点下创建了外部链接,当我遍历根节点下的节点时,得到以下输出:

I created external links under the root node and when i traverse the nodes under the root, i get the following output :

/link1(ExternalLink)->/files/data1.h5:/weights/Image
/link2(ExternalLink)->/files/data2.h5:/weights/Image

/link1 (ExternalLink) -> /files/data1.h5:/weights/Image
/link2 (ExternalLink) -> /files/data2.h5:/weights/Image

以此类推,

我知道要取消引用链接,可以通过以下方式使用自然命名来完成此操作:

I know that for de-referencing a link, it can be done like this, using natural naming in the below manner:

f = open_file('collection.h5',mode='r')
plink1 = f.root.link1()
plink2 = f.root.link2()

但是我想在for循环中执行此操作,对此有任何帮助吗?

but I want to do this in a for-loop, any help regarding this?

推荐答案

当您在任何组级别都具有ExternalLink时,这是一个更完整(鲁棒且复杂)的答案,可以处理一般情况.它与上面类似,但是使用walk_nodes(),因为它在根级别具有3个组,并包含一个针对ExternalLink类型的测试(请参见isinstance()).此外,它还显示了如何使用_v_children属性来获取节点字典. (我无法通过list_nodes()使用ExternalLink.)

This is a more complete (robust and complicated) answer to handle the general condition when you have an ExternalLink at any group level. It is similar to above, but uses walk_nodes() because it has 3 groups at the root level, and includes a test for ExternalLink types (see isinstance()). Also, it shows how to use the _v_children attribute to get a dictionary of nodes. (I couldn't get list_nodes() to work with an ExternalLink.)

import tables as tb
import glob

h5f = tb.open_file('collection.h5',mode='w')
link_cnt = 0
pre_list = ['SO_53', 'SO_54', 'SO_55']
for h5f_pre in pre_list :
    h5f_pre_grp = h5f.create_group('/', h5f_pre)
    for h5name in glob.glob('./'+h5f_pre+'*.h5'):
        link_cnt += 1
        h5f.create_external_link(h5f_pre_grp, 'link_'+'%02d'%(link_cnt), h5name+':/')
h5f.close()

h5f = tb.open_file('collection.h5',mode='r')
for link_node in h5f.walk_nodes('/') : 
    if isinstance(link_node, tb.link.ExternalLink) :
        print('\nFor Node %s:' % (link_node._v_pathname) )
        print("``%s`` is an external link to: ``%s``" % (link_node, link_node.target))
        plink = link_node(mode='r') # this returns a file object for the linked file
        linked_nodes = plink._v_children
        print (linked_nodes)

h5f.close()

这篇关于如何使用pytables取消引用外部链接列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆