Dear experts,
sorry to go back to this issue, but really I don’t understand what is going on. This it the classic example of the problem:
import ROOT
histo_file = ROOT.TFile.Open("histo_file.root", "recreate")
histo = ROOT.TH1F()
histo.SetName("h")
histo.Write()
histo_file.Close()
del histo_file
del histo
# program start here
output_file = ROOT.TFile("output.root", "recreate")
output_tree = ROOT.TTree("output_tree", "output_tree")
output_tree.SetDirectory(output_file)
histo_file = ROOT.TFile("histo_file.root")
histo = histo_file.Get("h")
histo_file.Close()
output_tree.Fill()
output_tree.Write()
# --> Error in <TROOT::WriteTObject>: The current directory (PyROOT) is not associated with a file. The object (output_tree) has not been written.
I understand the problem, but I don’t understand why the following solution do not work.
Main question: what’s the best way to avoid it (without changing the order of I/O)?
Secondary question: is there a way to disable current directory / current file and to tell to ROOT where to save the TTree? I was thinking that adding the line
output_tree.SetDirectory(output_file) # write it there, not in the current directory
was doing the job. But it doesn’t.
If I print
print output_tree.GetDirectory()
print ROOT.gDirectory
print ROOT.gFile
before opening the first file I get three times the same object. After they are different, except for the fist which is unchanged, so I am trying to do:
output_file = ROOT.TFile("output.root", "recreate")
output_tree = ROOT.TTree("output_tree", "output_tree")
output_tree.SetDirectory(output_file)
histo_file = ROOT.TFile("histo_file.root")
histo = histo_file.Get("h")
histo_file.Close()
# force them to be to point to the right one
ROOT.gDirectory = output_tree.GetDirectory()
ROOT.gFile = output_tree.GetDirectory()
print output_tree.GetDirectory()
print ROOT.gDirectory
print ROOT.gFile
output_tree.Fill()
output_tree.Write()
now the three last prints tell me that the three object are the same: gDirectory and gFile are pointing to the TFile I have created, but still the error.
I have noticed also that ROOT. 5.34/18 this code run (do not work properly), while in 5.34/20 I get
RuntimeError: property type mismatch or assignment not allowed
I solved with
output_tree.GetCurrentFile().Write()
but I really do not understand it. And in addition, what happens if I force the TTree to flush before writing?