SimpleIO_py.ipynb Open in SWAN Download

Simple IO


This simple ROOTbook shows how to create a [histogram](https://root.cern.ch/doc/master/classTH1F.html), [fill it](https://root.cern.ch/doc/master/classTH1.html#a77e71290a82517d317ea8d05e96b6c4a) and [write it](https://root.cern.ch/doc/master/classTObject.html#a19782a4717dbfd4857ccd9ffa68aa06d).
In [1]:
import ROOT
Welcome to JupyROOT 6.07/07
In [2]:
%jsroot on

We now define a function that will create a histogram, fill it and write it to a file. Later, we will read back the histogram from disk.

In [5]:
def writeHisto(outputFileName):
    outputFile = ROOT.TFile(outputFileName, "RECREATE")
    h = ROOT.TH1F("theHisto","My Test Histogram;X Title; Y Title",64, -4, 4)
    h.FillRandom("gaus")
    # now we write to the file
    h.Write()

All objects the class of which has a dictionary can be written on disk. By default, the most widely used ROOT classes are shipped with a dictionary: the histogram is one of those. Writing on a file is as simple as invoking the Write method.

Now we invoke the function:

In [6]:
writeHisto("output.root")

Before reading the object, we can check from the commandline the content of the file with the rootls utility:

In [8]:
%%bash
rootls -l output.root
TH1F  Apr 12 14:06  theHisto  "My Test Histogram"

We see that the file contains one object of type TH1F, the name of which is theHisto and the title of which is My Test Histogram.

Let's now use the ROOT interface to read it and draw it:

In [10]:
inputFile = ROOT.TFile("output.root")
h = inputFile.theHisto
c = ROOT.TCanvas()
h.Draw()
c.Draw()

And that's it!