Histogram becomes None when input file is closed

Hi,

In the following code, I want to loop over histograms from different files and clone them into a dictionary for later analysis. However, when I close the file, the histogram returns None.

def get_histograms_per_process(input_files):
    histograms = {}
    for file_ in input_files:
        print("file name ==>", file_)
        f_read = TFile(file_, "READ")
        for key in f_read.GetListOfKeys():
            h = key.ReadObj()
            h.SetDirectory(0)
            if h.ClassName() == 'TH1F':
                histogram = f_read.Get(h.GetName())
                histo_entries = histogram.GetEntries()
                if histo_entries == 0:
                     continue
                else:
                    histograms[h.GetName()] = histogram.Clone()

        f_read.Close()
        
    print("Histograms from the function get_histograms_per_process:", histograms)
    return histograms

If I don’t close the file, it returns values for histograms in the last file in the loop, while the previous files return None. It appears that the histograms are not being detached from the file although I am using h.SetDirectory(0). Any suggestions for overcoming this?

Thank you,
Ali

Hi,

You should modify your code to call SetDirectory only for histogram objects.
Like:

def get_histograms_per_process(input_files):
    histograms = {}
    for file_ in input_files:
        print("file name ==>", file_)
        f_read = TFile(file_, "READ")
        for key in f_read.GetListOfKeys():
            if key.GetClassName() == 'TH1F':
                histogram = key.ReadObj()
                histogram.SetDirectory(0)
                histo_entries = histogram.GetEntries()
                if histo_entries == 0:
                     continue
                else:
                    histograms[histogram.GetName()] = histogram

        f_read.Close()
        
    print("Histograms from the function get_histograms_per_process:", histograms)
    return histograms

In such case you also not need to clone histogram.

Thank you so much! it works.

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