pyROOT changing and writing to subdirectory

Hi!

I’m currently trying to write a histogram from a dataframe to a .root files subdirectory. The creation of the directory works and writing of the histogram, but it doesn’t go to the subdirectory. The problem is probably when changing the working directory, so how should it be done?

The code looks like (there’s some minor stuff before this):

myFile = ROOT.TFile.Open(outFileName, "RECREATE")

eta_low = 0.5
eta_up = eta_low+0.5
limits = f"Jet_pt[(abs(Jet_eta) < {eta_up}) && (abs(Jet_eta) > {eta_low}) && (Jet_pt > {pt_val})]"
dir_name = f"eta_{str(eta_low)}-{str(eta_up)}"
hist = df.Define("pT", limits).Histo1D("pT")
    
etadir = myFile.mkdir(dir_name)
cd = myFile.cd(dir_name)
myFile.WriteObject(hist.GetPtr(), "pT")

Thanks :slight_smile:

I now got it working as wanted with gDirectory by changing the last few lines such that:

etadir = myFile.mkdir(dir_name)
etadir.cd()
ROOT.gDirectory.WriteObject(hist.GetPtr(), "pT")
myFile.Close()

Hi @ntoikka ,

welcome to the ROOT forum and sorry for the high latency, this must have slipped through the cracks!

I think myFile.cd(dir_name) should be etadir.cd() and then etadir.WriteObject(...), @pcanal can confirm. I’m glad you found a workaround though.

Cheers,
Enrico

cd = myFile.cd(dir_name)

makes 'dir_name' the “current” directory (the value of gDirectory)

myFile.WriteObject(hist.GetPtr(), "pT")

explicitly request to (ignore gDirectory and to) write the object in the ‘directory’ myFile (the pointer to the file is also the pointer to the top level directory of the file).

Yes that would work too.