Split Root File in two separate Files

Hey all,

I am using a root file to read values from it, the file is called main.root. The root file consists of a tree “myvalues” and several branches like “Energy”, “Momentum”, “Event”.
Now I would like to separate my main.root file in two different root files main1.root and main2.root depending on the Event Variable that can either be 0 or 1. In the case of 0, I would like to save all the values from this line in the table (Energy, Momentum, Event) in the file main1.root. When the Event Variable is 1, I would like to save all values (Energy, Momentum, Event) in the main2.root file.

I searched that this can be possible with the TTreeReaderValue.

TFile file(“main.root”);
TTree* tree = (TTree*) file.Get(“myvalues”);
TTreeReaderValue var_event(reader, “Event”);
TTreeReaderValue var_energy(reader, “Energy”);

while (reader.Next()) {
std::cout<< "Eventvalue: "<<*var_event<< std::endl;

Unfortunately I dont know how to save these values. Is this done with a chain?

_ROOT Version: 6.20.04
_Platform: Ubuntu 18.04.5 LTS (Bionic Beaver)
_Compiler: gcc -v 7.5.0

If it’s a simple selection and you want to copy all branches, you don’t need a TTreeReader, since a CopyTree will do it. In short: open the original file, get the tree, create the 2 new files, do the 2 tree copies, save each copy to a file:

  TFile *f = new TFile("main.root");
  TTree *T = (TTree*)f->Get("myvalues");

  TFile *f1 = new TFile("main1.root","RECREATE");
  TTree *T1 = T->CopyTree("Event==0");
  f1->cd();  // make sure T1 goes to f1
  // ... and similar for the second tree/file

Many thanks! That worked. It helped me a lot.