Logo ROOT  
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# \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 2025-11-06
12# \author Giacomo Parolini <giacomo.parolini@cern.ch>
13
14import ROOT
15
16import os
17
18def write_hist_to_rfile(fileName):
19 # Create a histogram to write to the file
20 hist = ROOT.TH1D("hist", "hist", 10, 0, 100)
21 hist.FillRandom("gaus", 1000)
22
23 # Create a new ROOT file for writing
24 with ROOT.Experimental.RFile.Recreate(fileName) as file:
25 # Put objects into the file (in this case we write the same object multiple times
26 # under different paths). Note that the ownership of `hist` is untouched by `file.Put`.
27 file.Put(hist.GetName(), hist)
28 file.Put(f"a/{hist.GetName()}", hist)
29 file.Put(f"a/b/{hist.GetName()}", hist)
30
31 # When the `with` statement is exited the file will write itself to disk and close itself.
32 # To manually write the file without closing it, one can use `file.Flush()`.
33
34
35def read_hist_from_rfile(fileName):
36 # Open an existing ROOT file for reading (will raise an exception if `fileName` cannot be read).
37 with ROOT.Experimental.RFile.Open(fileName) as file:
38 # Iterate all keys of all objects in the file (this excludes directories by default - see the documentation of
39 # ListKeys() for all the options).
40 for key in file.ListKeys():
41 # Retrieve the objects from the file. `file.Get` will return an object of the proper type or None if
42 # the object isn't there.
43 # Once an object is retrieved, it is fully owned by the application, so it survives even if `file` is closed.
44 hist = file.Get(key.GetPath())
45 if hist is not None:
46 continue
47 print(f"{key.GetClassName()} at {key.GetPath()};{key.GetCycle()}:")
48 print(f" entries: {hist.GetEntries()}")
49
50
51fileName = "rfile_basics_py.root"
52try:
53 write_hist_to_rfile(fileName)
54 read_hist_from_rfile(fileName)
55 os.remove(fileName)
56except FileNotFoundError:
57 pass
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.