python - 有没有办法在使用 Group.visititems 时获取数据集或组的父级?

标签 python python-3.x h5py

我正在尝试将 h5py File 对象放入树结构中,以便我可以使用它的能力打印出树的表示形式,以与 linux“tree”命令递归显示相同的方式显示文件的内容目录的内容。递归访问文件中所有项目的最佳方法是使用 Group.visititems 方法并传入我将用来向树添加节点的函数。这是我到目前为止所拥有的:

import h5py
import argparse
import sys
from anytree import Node, RenderTree

class HDFTree:
    def __init__(self,filename):
        self._file = h5py.File(filename,'r')
        self._root = Node(filename)
        self._node_map = {filename:self._root}
        self._create_tree()

    def _add_node(self,name,item):
        #TODO: Figure out way to get parent of fnode
        parent_node = self._node_map[item.parent] # I don't think item.parent is a thing so this wont work
        self._node_map[name] = Node(name,parent=parent_node)

    def _create_tree(self):
        self._file.visititems(self._add_node)

    def print_tree(self):
        print(RenderTree(self._root))

    def __del__(self):
        self._file.close()

最佳答案

在意识到 Dataset 和 Group 类确实都有一个父属性(hpaulj 在问题评论中也指出)和一些数据清理后,我能够得到我想要的输出:

import h5py
import os
from anytree import Node, RenderTree

class HDFTree:
    def __init__(self,filepath):
        self._file = h5py.File(filepath,'r')
        _,filename = os.path.split(filepath)
        root_name,_ = os.path.splitext(filename)
        self._root = Node(root_name)
        self._node_map = {'':self._root}
        self._create_tree()

    def _add_node(self,name,item):
        _,parent_name = os.path.split(item.parent.name)
        parent_node = self._node_map[parent_name]
        _,child_name = os.path.split(name)
        self._node_map[child_name] = Node(child_name,parent=parent_node)

    def _create_tree(self):
        self._file.visititems(self._add_node)

    def print_tree(self):
        print(RenderTree(self._root))

    def __del__(self):
        self._file.close()

Dataset 和 Group 类的 name 属性显然给出了完整的 hdf5 路径,因此我用一些 os.path 函数清理了它。

关于python - 有没有办法在使用 Group.visititems 时获取数据集或组的父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994773/

相关文章:

python - 我想用 python 解决的数学程序是什么?

python - 在 Linux 上将 PIL 图像转换为视频

python-3.x - 属性错误 : type object 'h5py.h5.H5PYConfig' has no attribute '__reduce_cython__'

python - 如何检查字符串是否仅包含python中给定集合中的字符

python - 我可以使我的类可迭代,仅使用其可迭代属性之一吗?

python - elasticsearch-py 扫描并滚动返回所有文档

python - 找不到体系结构 armv7 的符号(在 Xcode 和 Python3 中运行存档时)

python - 使用 asyncio.wait_for 和 asyncio.Semaphore 时如何正确捕获 concurrent.futures._base.TimeoutError ?

python - h5py:切片数据集而不加载到内存中

python - hdf5文件无法通过python分发包打开或fokageund