#!/usr/bin/env python # coding: utf-8 # # 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 # In[2]: get_ipython().run_line_magic('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](https://root.cern.ch/doc/master/classTObject.html#a19782a4717dbfd4857ccd9ffa68aa06d). # # 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](https://root.cern.ch/how/how-quickly-inspect-content-file): # In[8]: get_ipython().run_cell_magic('bash', '', 'rootls -l output.root\n') # 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!