简体   繁体   中英

What is a way of accessing arbitrary groups in hdf5 file using pytables?

Want to access/create an arbitrary group in an HDF5 db file using pytables. The file has the following structure:

db
  |_ user_00                  # Group
       |_  subjectTable   # TableObject  
       |_ subject_00       # GroupObject

Registring a new subject means adding a row to the subjectTable and creating a group with the subject name so I have:

    def open_db(db_file, mode='r+'):
        h5f = tables.openFile(db_file, mode)
        return h5f

    def register_new_subject(subjectName, user, db_file):
        # Open db
        h5f = open_db(db_file)

        #Create subject
        subjectGroup = h5f.createGroup(h5f.root.??????????, subjectName)

        # Add subjectName to user/subjectTable
        ...

As you can see by the question marks I don't know how to continue... because the group is specific to the user I got stuck, the new group should be h5f.root.[user].subjectName

is there a way of doing this?

better still is there a pytables way of doing this?

for extra points is there a pythonic way of doing this?

EDIT : This way it works, however I hate using eval().

    row_str = 'h5f.root.{}'.format(user)
    where = eval(row_str)
    subjectGroup = h5f.createGroup(where, subjectName)

Any other way of doing this?

row_str = 'h5f.root.{}'.format(user)
    where = eval(row_str)
    subjectGroup = h5f.createGroup(where, subjectName)

It is very simple, as the createGroup method accepts a path string for the where argument, and you can accomplish what you want as:

subjectGroup = h5f.createGroup('/{}'.format(user), subjectName, createparents=True)

createGroup even has an argument (as indicated above) to force the creation of the full path if the parent node(s) do not exist.

If you need some check for the parent group existence, I would probably use the pytables file-object getNode for evaluating handles to specific nodes

try:
    where = h5f.getNode('/{}'.format(user))
except:
    raise ValueError('User node does not exist in file') # or exception of your choosing

subjectGroup = h5f.createGroup(where, subjectName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM