Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rfile002_rntuple.py
Go to the documentation of this file.
1# \file
2# \ingroup ROOT7 tutorial_io
3# Demonstrate how to read/write an RNTuple with RFile
4#
5# \macro_code
6# \macro_output
7#
8# \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
9# is welcome!
10#
11# \date 2026-10-12
12# \author Giacomo Parolini <giacomo.parolini@cern.ch>
13
14import ROOT
15
16import os
17
18
19def write_rntuple_to_rfile(fileName):
20 # Create a new ROOT file for writing
21 with ROOT.Experimental.RFile.Recreate(fileName) as file:
22 # Define the RNTuple schema
24 model.MakeField["int"]("intField")
25 # Create an RNTupleWriter to append to the RFile
26 with ROOT.RNTupleWriter.Append(model, "ntuple", file) as writer:
27 entry = writer.CreateEntry()
28
29 # Fill the RNTuple with data
30 for i in range(10):
31 entry["intField"] = i
32 writer.Fill(entry)
33
34 # `writer` will write the data to file upon exiting the with statement....
35 # ...then `file` will write itself to disk in turn when exiting the outer with statement.
36
37
38def read_rntuple_from_rfile(fileName):
39 # Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read).
40 with ROOT.Experimental.RFile.Open(fileName) as file:
41 # Get back the RNTuple anchor from the file
42 rntuple = file.Get("ntuple")
43
44 # Create an RNTupleReader from the anchor
45 with ROOT.RNTupleReader.Open(rntuple) as reader:
46 entry = reader.CreateEntry()
47 for i in reader.GetEntryRange():
48 reader.LoadEntry(i, entry)
49 print(f"value[{i}] = {entry['intField']}")
50
51
52fileName = "rfile_rntuple_py.root"
53try:
54 write_rntuple_to_rfile(fileName)
55 read_rntuple_from_rfile(fileName)
56 os.remove(fileName)
57except FileNotFoundError:
58 pass
static std::unique_ptr< RFile > Open(std::string_view path, const ROpenOptions &opts=ROpenOptions())
Opens the file for reading.
Definition RFile.cxx:204
static std::unique_ptr< RFile > Recreate(std::string_view path, const RRecreateOptions &opts=RRecreateOptions())
Opens the file for reading/writing, overwriting it if it already exists.
Definition RFile.cxx:226
static std::unique_ptr< RNTupleModel > Create()
static std::unique_ptr< RNTupleReader > Open(std::string_view ntupleName, std::string_view storage, const ROOT::RNTupleReadOptions &options=ROOT::RNTupleReadOptions())
Open an RNTuple for reading.
static std::unique_ptr< RNTupleWriter > Append(std::unique_ptr< ROOT::RNTupleModel > model, std::string_view ntupleName, TDirectory &fileOrDirectory, const ROOT::RNTupleWriteOptions &options=ROOT::RNTupleWriteOptions())
Creates an RNTupleWriter that writes into an existing TFile or TDirectory, without overwriting its co...