TH1D within a dir, within ANOTHER dir of a RootFile

Hi, I have a short question for this intelligent and helpful website again!

In my python script, I have short lines where I open a .root file and define my object as TH1D in the rootfile.

HOWEVER, the TH1Ds are in a directory, within ANOTHER directory of the root file.

My root file consists in hierarchy of
forCI.root - ak7 - y_0.0-0.5 - Two TH1D histograms (EwkCor, NPCor)

In my python code, I have

    fEWK = TFile('forCT.root')
    hEWK = fEWK.Get('EwkCor')
    if hEWK == None:
        hutil.error('smearSpectra.py',
                    "can't get EWK histogram EwkCor")

Obviously, it leads to an error message that it can’t get the histogram.

Thus, I modified the code a bit such that I have,

    fEWK = TFile('forCT.root')
    eEWK = fEWK.cd('ak7')
    dEWK = eEWK.cd('y_0.0-0.5')
    hEWK = dEWK.Get('EwkCor')
    if hEWK == None:
        hutil.error('smearSpectra.py',
                    "can't get EWK histogram EwkCor")

Then, I obtain message that says

Traceback (most recent call last):
File “practicesmear.py”, line 325, in
main()
File “practicesmear.py”, line 199, in main
dEWK = eEWK.cd(‘y_0.0-0.5’)
AttributeError: ‘bool’ object has no attribute ‘cd’

Does anyone know how to define my object as a TH1D, which is within TWO hierarchy of directories of my .root file?

Thank you so much.

According to the message you get it seems eEWKyou got from eEWK = fEWK.cd('ak7') is considered as a bool by python. And of course cd will not work on a bool … May be @etejedor` can help you.

TFile inherits from TDirectoryFile, which has method

TDirectory * TDirectoryFile::GetDirectory 	( 	const char *  	apath,
		Bool_t  	printError = false,
		const char *  	funcname = "GetDirectory" 
	)

(https://root.cern.ch/doc/master/classTDirectoryFile.html#a3d653f62f9232377f74cc2a8024d014a)

Thanks for the response.

As a newbie, the document is a bit confusing to read.

Do you think you could provide what the lines would look like in my example?

Thank you!

I would say this fEWK.GetDirectory('/ak7/y_0.0-0.5').Get('EwkCor') should work.
Or just this fEWK.Get('ak7/y_0.0-0.5/EwkCor').

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.