Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rfile003_ttree.py
Go to the documentation of this file.
1# \file
2# \ingroup ROOT7 tutorial_io
3# Demonstrate how to read a TTree with RFile.
4#
5# Note that, due to how TTree handles lifetime and its relationship with TDirectory, writing TTree through RFile
6# is currently unsupported.
7#
8# \macro_code
9# \macro_output
10#
11# \date 2026-10-12
12# \author Giacomo Parolini <giacomo.parolini@cern.ch>
13
14import array
15import os
16
17import ROOT
18
19
20def read_ttree_from_rfile(fileName):
21 # Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read).
22 # IMPORTANT! This file must remain open while reading data from the tree.
23 with ROOT.RFile.Open(fileName) as file:
24 # Get back the TTree from the file
25 tree = file.Get("tree")
26 floatVal = array.array("f", [0])
27 tree.SetBranchAddress("floatBranch", floatVal)
28
29 for i in range(tree.GetEntries()):
30 tree.GetEntry(i)
31 print(f"value[{i}] = {floatVal[0]}")
32
33
34fileName = "rfile_ttree_py.root"
35try:
36 # Note that TTree cannot be written to RFile, so we use RDataFrame to write it instead.
37 ROOT.RDataFrame(10).Define("floatBranch", "static_cast<float>(rdfentry_)").Snapshot("tree", fileName)
38
39 read_ttree_from_rfile(fileName)
40 os.remove(fileName)
41except FileNotFoundError:
42 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:204