Histogram is empty when writing it to a new root file

Hello all,

I am trying to copy a histogram from file X.root to Y.root since I do not want to deal with directories in python. However, when I open the histogram written to file Y.root, the histogram is empty. Do you have an idea of how to fix this?

void test_open_roc(){
	TFile *f = new TFile("TMVA_250_300.root");
	TDirectory *f2 = (TDirectory*)f->Get("dataset;1");
	TDirectory *f3 = (TDirectory*)f2->Get("Method_Cuts;1");
	TDirectory *f4 = (TDirectory*)f3->Get("Cuts;1");
	TH1F *h = (TH1F*)f4->Get("MVA_Cuts_effBvsS");

	TFile * newf = new TFile("histTMVA_250_300.root","RECREATE");

The simplest way to do that is to use the command line tool rootcp

% rootcp --help
usage: rootcp [-h] [-c COMPRESS] [--recreate] [-r] [--replace] SOURCE [SOURCE ...] DEST

Copy objects from ROOT files into an other

positional arguments:
  SOURCE                Source file
  DEST                  Destination file

optional arguments:
  -h, --help            show this help message and exit
  -c COMPRESS, --compress COMPRESS
                        change the compression settings of the destination file (if not already existing).
  --recreate            recreate the destination file.
  -r, --recursive       recurse inside directories
  --replace             replace object if already existing

Note: If an object has been written to a file multiple times, rootcp will copy only the latest version of that object.

- rootcp source.root dest.root
  Copy the latest version of each object in 'source.root' to 'dest.root'.

- rootcp source.root:hist* dest.root
  Copy all histograms whose names start with 'hist' from 'source.root' to 'dest.root'.

- rootcp source1.root:hist1 source2.root:hist2 dest.root
  Copy histograms 'hist1' from 'source1.root' and 'hist2' from 'source2.root' to 'dest.root'.

- rootcp --recreate source.root:hist dest.root
  Recreate 'dest.root' and copy the histogram named 'hist' from 'source.root' into it.

- rootcp -c 1 source.root:hist dest.root
  Change compression factor of 'dest.root' if not existing and copy the histogram named 'hist' from 'source.root' into it.

For the record you are missing the writing of the file

	TFile * newf = new TFile("histTMVA_250_300.root","RECREATE");

@naikal_mc Try:

  TFile *f = TFile::Open("TMVA_250_300.root");
  TH1F *h; f->GetObject("dataset/Method_Cuts/Cuts/MVA_Cuts_effBvsS", h);
  if (h) h->Print("base"); else std::cout << "No h!" << std::endl;

@pcanal Sorry, but you are wrong. Try:

  TFile *f = TFile::Open("hsimple.root");
  TH1F *h; f->GetObject("hpx", h);
  // h->Print();
  TFile *newf = TFile::Open("hsimple.new.root", "RECREATE");
  // newf->Close(); // not needed
  delete newf;
  delete f; // automatically deletes h, too
1 Like

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