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# \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
12# is welcome!
13#
14# \date 2026-10-12
15# \author Giacomo Parolini <giacomo.parolini@cern.ch>
16
17import array
18import os
19
20import ROOT
21
22
23def read_ttree_from_rfile(fileName):
24 # Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read).
25 # IMPORTANT! This file must remain open while reading data from the tree.
26 with ROOT.Experimental.RFile.Open(fileName) as file:
27 # Get back the TTree from the file
28 tree = file.Get("tree")
29 floatVal = array.array("f", [0])
30 tree.SetBranchAddress("floatBranch", floatVal)
31
32 for i in range(tree.GetEntries()):
33 tree.GetEntry(i)
34 print(f"value[{i}] = {floatVal[0]}")
35
36
37fileName = "rfile_ttree_py.root"
38try:
39 # Note that TTree cannot be written to RFile, so we use RDataFrame to write it instead.
40 ROOT.RDataFrame(10).Define("floatBranch", "static_cast<float>(rdfentry_)").Snapshot("tree", fileName)
41
42 read_ttree_from_rfile(fileName)
43 os.remove(fileName)
44except FileNotFoundError:
45 pass
static std::unique_ptr< RFile > Open(std::string_view path, const ROpenOptions &opts=ROpenOptions())
Opens the file for reading.
Definition RFile.cxx:204
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...