Testing file open with TFile.Open()

I prefer to use TFile.Open to get a open ROOT files, rather than just TFile because TFile.Open can open ROOT files in dcache filesystems, and TFile cannot.

But I cannot figure out if you have opened a file correctly using TFile.Open. The IsZombie() method does not work because TFile.Open returns a nil pointer if it fails:

f = TFile.Open(“xxx.root”)
Error in TFile::TFile: file xxx.root does not exist
f
<ROOT.TFile object at 0x(nil)>

You cannot call TFile methods with a nil pointer. I have not figured out how to test the the pointer is nil. Tests f==0 or f==NULL do not work (in the sense that they generate a python error(in contrast in C++ testing f==0 does not generate an error)

… well I figured out an indirect method of testing if the file opened:

f = TFile.Open(fname)
try:
f.IsZombie()
except:
print ‘ERROR: Fail to open’,fname
sys.exit(0)

the IsZombie() is irrelevant – just trying any TFile method will fail if f is not a valid TFile object.

Any other suggestions?

You can check if the file is valid like you would usually in C++:

import ROOT as r
f = r.TFile.Open('bla.root')
if f:
    print('is open')
else:
    print('ups')

This is equivalent to checking f!=None (but one wouldn’t write that like that since it is redundant, just like checking if a bool is equal to true/false).

Thanks for your reply. Since I only want to know if the file is not open I prefer this version

if not f:
print ‘file is not open’