ROOT
master
Reference Guide
Loading...
Searching...
No Matches
rfile001_basics.py
Go to the documentation of this file.
1
# \file
2
# \ingroup ROOT7 tutorial_io
3
# Demonstrate the basic usage of RFile.
4
#
5
# \author Giacomo Parolini <giacomo.parolini@cern.ch>
6
# \date 2025-11-06
7
# \macro_code
8
# \macro_output
9
# \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
10
# is welcome!
11
12
import
ROOT
13
14
import
os
15
16
def
write_hist_to_rfile
(fileName):
17
# Create a histogram to write to the file
18
hist =
ROOT.TH1D
(
"hist"
,
"hist"
, 10, 0, 100)
19
hist.FillRandom
(
"gaus"
, 1000)
20
21
# Create a new ROOT file for writing
22
with
ROOT.Experimental.RFile.Recreate
(fileName)
as
file:
23
# Put objects into the file (in this case we write the same object multiple times
24
# under different paths). Note that the ownership of `hist` is untouched by `file.Put`.
25
file.Put
(
hist.GetName
(), hist)
26
file.Put
(f
"a/{hist.GetName()}"
, hist)
27
file.Put
(f
"a/b/{hist.GetName()}"
, hist)
28
29
# When the `with` statement is exited the file will write itself to disk and close itself.
30
# To manually write the file without closing it, one can use `file.Flush()`.
31
32
33
def
read_hist_from_rfile
(fileName):
34
# Open an existing ROOT file for reading (will raise an exception if `fileName` cannot be read).
35
with
ROOT.Experimental.RFile.Open
(fileName)
as
file:
36
# Iterate all keys of all objects in the file (this excludes directories by default - see the documentation of
37
# ListKeys() for all the options).
38
for
key
in
file.ListKeys
():
39
# Retrieve the objects from the file. `file.Get` will return an object of the proper type or None if
40
# the object isn't there.
41
# Once an object is retrieved, it is fully owned by the application, so it survives even if `file` is closed.
42
hist =
file.Get
(
key.GetPath
())
43
if
hist
is
not
None
:
44
continue
45
print(f
"{key.GetClassName()} at {key.GetPath()};{key.GetCycle()}:"
)
46
print(f
" entries: {hist.GetEntries()}"
)
47
48
49
fileName =
"rfile_basics_py.root"
50
try
:
51
write_hist_to_rfile
(fileName)
52
read_hist_from_rfile
(fileName)
53
os.remove
(fileName)
54
except
FileNotFoundError:
55
pass
TRangeDynCast
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Definition
TCollection.h:359
ROOT::Detail::TRangeCast
Definition
TCollection.h:312
tutorials
io
experimental
rfile001_basics.py
ROOT master - Reference Guide Generated on Wed Nov 19 2025 14:06:29 (GVA Time) using Doxygen 1.10.0