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# \date 2026-10-12
9# \author Giacomo Parolini <giacomo.parolini@cern.ch>
10
11import ROOT
12
13import os
14
15
16def write_rntuple_to_rfile(fileName):
17 # Create a new ROOT file for writing
18 with ROOT.RFile.Recreate(fileName) as file:
19 # Define the RNTuple schema
21 model.MakeField["int"]("intField")
22 # Create an RNTupleWriter to append to the RFile
23 with ROOT.RNTupleWriter.Append(model, "ntuple", file) as writer:
24 entry = writer.CreateEntry()
25
26 # Fill the RNTuple with data
27 for i in range(10):
28 entry["intField"] = i
29 writer.Fill(entry)
30
31 # `writer` will write the data to file upon exiting the with statement....
32 # ...then `file` will write itself to disk in turn when exiting the outer with statement.
33
34
35def read_rntuple_from_rfile(fileName):
36 # Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read).
37 with ROOT.RFile.Open(fileName) as file:
38 # Get back the RNTuple anchor from the file
39 rntuple = file.Get("ntuple")
40
41 # Create an RNTupleReader from the anchor
42 with ROOT.RNTupleReader.Open(rntuple) as reader:
43 entry = reader.CreateEntry()
44 for i in reader.GetEntryRange():
45 reader.LoadEntry(i, entry)
46 print(f"value[{i}] = {entry['intField']}")
47
48
49fileName = "rfile_rntuple_py.root"
50try:
51 write_rntuple_to_rfile(fileName)
52 read_rntuple_from_rfile(fileName)
53 os.remove(fileName)
54except FileNotFoundError:
55 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...