example of macro to read data from an ascii file and create a root file with a Tree.
NOTE: comparing the results of this macro with those of staff.C, you'll notice that the resultant file is a couple of bytes smaller, because the code below strips all white-spaces, whereas the .C version does not.
import re, array, os
import ROOT
from ROOT import TFile, TTree, gROOT, AddressOf
gROOT.ProcessLine(
"struct staff_t {\
Int_t Category;\
UInt_t Flag;\
Int_t Age;\
Int_t Service;\
Int_t Children;\
Int_t Grade;\
Int_t Step;\
Int_t Hrweek;\
Int_t Cost;\
Char_t Division[4];\
Char_t Nation[3];\
};" );
staff = ROOT.staff_t()
f =
TFile(
'staff.root',
'RECREATE' )
tree =
TTree(
'T',
'staff data from ascii file' )
tree.Branch( 'staff', staff, 'Category/I:Flag:Age:Service:Children:Grade:Step:Hrweek:Cost' )
tree.Branch( 'Divisions', AddressOf( staff, 'Division' ), 'Division/C' )
tree.Branch( 'Nation', AddressOf( staff, 'Nation' ), 'Nation/C' )
fname = os.path.join(str(ROOT.gROOT.GetTutorialDir()), 'tree', 'cernstaff.dat')
for line
in open(fname).readlines():
t = list(filter( lambda x: x, re.split( '\s+', line ) ) )
staff.Category = int(t[0])
staff.Flag = int(t[1])
staff.Age = int(t[2])
staff.Service = int(t[3])
staff.Children = int(t[4])
staff.Grade = int(t[5])
staff.Step = int(t[6])
staff.Hrweek = int(t[7])
staff.Cost = int(t[8])
staff.Division = t[9]
staff.Nation = t[10]
tree.Fill()
tree.Print()
tree.Write()
if __name__ == '__main__':
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format.
A TTree represents a columnar dataset.
- Author
- Wim Lavrijsen
Definition in file staff.py.