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