Reputation: 386
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?
Upvotes: 2
Views: 1117
Reputation: 71
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)
Upvotes: 3
Reputation: 386
row_str = 'h5f.root.{}'.format(user)
where = eval(row_str)
subjectGroup = h5f.createGroup(where, subjectName)
Upvotes: 3