How to save selected events from a ROOT file to another file?

Hi!
I want to save a small subset of events with a certain branch from a series of rootfiles onto a single new rootfile.

file=0
chain = ROOT.TChain("cbmsim")
path="path/to/files/"
for inputFile in os.listdir(path):
	        file+=1        
	        if file>3: break
	        chain.Add(inputFile)

nrOfEvents = chain.GetEntries()      
newfile = ROOT.TFile("test.root", "recreate")
newtree = chain.CloneTree(0)
for i in range(nrOfEvents):
	    chain.GetEntry(i)
	    if hasattr(chain,"Digitised_Hits"): 
	       newtree.Fill()        
newfile.Write()
print('Done')

However, the above code gives me a segmentation fault when cloning the tree. How do I solve this?

Dear @praha ,

I believe the best tool for you would be RDataFrame


dataset_name = "cbmsim"
file_names = ["f1.root", "f2.root", "f3.root"]

df = ROOT.RDataFrame(dataset_name, file_names)
# You can further filter events here with the `Filter` operation.
# See the RDataFrame docs linked above

# This saves to an output TTree called `out_data` in file `out_file.root`
# storing only the `Digitised_Hits` column
df.Snapshot("out_data", "out_file.root", ["Digitised_Hits"])

Cheers,
Vincenzo

Hello,

I assume that Digitised_Hits is the branch name. Then what you can do is:

# deactivate all branches first
chain.SetBranchStatus( "*", 0 )
# then activate the branch you want
chain.SetBranchStatus( "Digitised_Hits", 1 );
# then clone the tree
newtree = chain.CloneTree( )