Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rfile003_ttree.py File Reference

Detailed Description

Demonstrate how to read a TTree with RFile.

Note that, due to how TTree handles lifetime and its relationship with TDirectory, writing TTree through RFile is currently unsupported.

import array
import os
import ROOT
def read_ttree_from_rfile(fileName):
# Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read).
# IMPORTANT! This file must remain open while reading data from the tree.
with ROOT.RFile.Open(fileName) as file:
# Get back the TTree from the file
tree = file.Get("tree")
floatVal = array.array("f", [0])
tree.SetBranchAddress("floatBranch", floatVal)
for i in range(tree.GetEntries()):
tree.GetEntry(i)
print(f"value[{i}] = {floatVal[0]}")
fileName = "rfile_ttree_py.root"
try:
# Note that TTree cannot be written to RFile, so we use RDataFrame to write it instead.
ROOT.RDataFrame(10).Define("floatBranch", "static_cast<float>(rdfentry_)").Snapshot("tree", fileName)
read_ttree_from_rfile(fileName)
os.remove(fileName)
except FileNotFoundError:
pass
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...
static std::unique_ptr< RFile > Open(std::string_view path, const ROpenOptions &opts=ROpenOptions())
Opens the file for reading.
Definition RFile.cxx:205
value[0] = 0.0
value[1] = 1.0
value[2] = 2.0
value[3] = 3.0
value[4] = 4.0
value[5] = 5.0
value[6] = 6.0
value[7] = 7.0
value[8] = 8.0
value[9] = 9.0
Date
2026-10-12
Author
Giacomo Parolini giaco.nosp@m.mo.p.nosp@m.aroli.nosp@m.ni@c.nosp@m.ern.c.nosp@m.h

Definition in file rfile003_ttree.py.