Looping over histograms in a root file

Dear all,
I’ve been having a few problems with a simple macro to loop over some .root files containing

file0 = TFile("run_" + runlist[0] + ".root")
dirList = gDirectory.GetListOfKeys()
for k1 in dirList: 
  h1 = k1.ReadObj()
  if (h1.GetClassName() == "TProfile"):
    print h1.ClassName(), " ", h1.GetClassName()
    print h1.GetMean(2)

The print statement gives this output for each of the TProfile objects:

TKey   TProfile

This gives all the histograms in the file, but when I try to get the mean of the histograms, it gives me:

  File "last5.py", line 34, in <module>
    print h1.GetMean(2)
AttributeError: 'TKey' object has no attribute 'GetMean'

I had an equivalent ROOT macro with the explicit cast:

TH1 *h2 = (TH1*)key2->ReadObj();
cout << h2->GetMean(2);

which worked fine. Do I need to do a cast in pyROOT or is there something else going on?

Thanks in advance,
Stewart Martin-Haugh,
University of Sussex


not sure how the code worked out, but the printout says that h2 is still a TKey carrying a TProfile, so to get to the histogram, another ReadObj() would be called for (and no, no casting is required at that point).


Thanks for the quick reply. I managed to solve the problem myself - the problem was that I was saving the TKeys rather than the histograms to the files.