Hey
I tried to use the pythonic approach to accessing the content of root file if I have a root tree inside the file by using:
file = TFile.Open("file.root")
myTree=file.myTree # this is the name of the tree in the file
for event in myTree:
print(event.x, event.y) # x and y are names of branches of the tree
and this works fine. Now if I put a tree into the folder inside a root file I have trouble using the above syntax. I know one could use Get
or GetObject
and then loop event by event. But I wonder if one can do something like:
file_with_folder = TFile.Open("file.root")
file_with_folder.cd("myFolder")
... (some more code) ...
myTree=file_with_folder.myTree # this is the name of the tree in the file
for event in myTree:
print(event.x, event.y) # x and y are names of branches of the tree
I know that in ROOT 6.14 one could use the RDataFrame to loop over all entries but unfortunately, I’m forced to use older versions of ROOT.
I figured that the difference is that if one has no folder the TTree key is available. At least that’s what file.ls()
says:
TFile** file.root
TFile* file.root
KEY: TTree myTree;1 this is a test tree
Then if one adds folder the file structure file_with_folder.ls()
gives:
TFile** file.root
TFile* file.root
KEY: TDirectoryFile data;1 data
which makes sense and if one does gDirectory.cd("data")
the file_with_dir.ls()
returns:
TFile** file.root
TFile* file.root
TDirectoryFile* data data
KEY: TTree myTree;1 this is a test tree
KEY: TDirectoryFile data;1 data
Key to the tree is now accessible but how can one use it? I tried the above example but I get:
for event in file.myTree:
AttributeError: TFile object has no attribute 'myTree'
which indicates that “myTree key is not visible” by file variable.
For clarity, I added two scripts that should do the same thing. Generate a tree, store it in a root file and read it back and do some example processing. Their only difference is that one of the produced root files has a directory in it and the other one doesn’t.
Any ideas
root_file_with_dir.py (1.0 KB)
root_file.py (728 Bytes)