Not able to use "with TFile("input_file_name.root", "read") as" block with root 6.24/06

I had installed root from conda and been using both root as well as pyroot but this particular method doesn’t work.

import ROOT
from ROOT import TFile
with TFile("new_out_file24.root", "read") as infile:
    hin = infile.Get("H1_Rprompt_302_to_303_qPE_pass_rCut_py_+model") 

print(hin.GetName())

I can read the file if I do it this way:

import ROOT
from ROOT import TFile
infile = TFile("new_out_file24.root", "read")
hin = infile.Get("H1_Rprompt_302_to_303_qPE_pass_rCut_py_+model") 
print(hin.GetName())
infile.Close()

ROOT Version: 6.24/06
Platform: Ubuntu 20.04
Compiler: Not Provided


Hello,

The context manager functionality for TFile that you are trying to use was added recently to master, there’s a tutorial for it:

It will be released with ROOT 6.28, so unfortunately you can’t use it yet with 6.24.

1 Like

Note however that

import ROOT
from ROOT import TFile
with TFile("new_out_file24.root", "read") as infile:
    hin = infile.Get("H1_Rprompt_302_to_303_qPE_pass_rCut_py_+model") 

print(hin.GetName())

will not work: because of ROOT lifetime management, the hin histogram is deleted when the file is closed. Maybe adding a hin.SetDirectory(0) would help in that case.

Ah yes, I didn’t had that in mind. Thanks for pointing it out.