Logo ROOT   6.10/09
Reference Guide
staff.py
Go to the documentation of this file.
1 ## \file
2 ## \ingroup tutorial_pyroot
3 ## \notebook -nodraw
4 ## example of macro to read data from an ascii file and
5 ## create a root file with a Tree.
6 ##
7 ## NOTE: comparing the results of this macro with those of staff.C, you'll
8 ## notice that the resultant file is a couple of bytes smaller, because the
9 ## code below strips all white-spaces, whereas the .C version does not.
10 ##
11 ## \macro_code
12 ##
13 ## \author Wim Lavrijsen
14 
15 import re, array, os
16 import ROOT
17 from ROOT import TFile, TTree, gROOT, AddressOf
18 
19 ## A C/C++ structure is required, to allow memory based access
20 gROOT.ProcessLine(
21 "struct staff_t {\
22  Int_t Category;\
23  UInt_t Flag;\
24  Int_t Age;\
25  Int_t Service;\
26  Int_t Children;\
27  Int_t Grade;\
28  Int_t Step;\
29  Int_t Hrweek;\
30  Int_t Cost;\
31  Char_t Division[4];\
32  Char_t Nation[3];\
33 };" );
34 
35 ## Function to read in data from ASCII file and fill the ROOT tree
36 def staff():
37 
38  staff = ROOT.staff_t()
39 
40  # The input file cern.dat is a copy of the CERN staff data base
41  # from 1988
42 
43  f = TFile( 'staff.root', 'RECREATE' )
44  tree = TTree( 'T', 'staff data from ascii file' )
45  tree.Branch( 'staff', staff, 'Category/I:Flag:Age:Service:Children:Grade:Step:Hrweek:Cost' )
46  tree.Branch( 'Divisions', AddressOf( staff, 'Division' ), 'Division/C' )
47  tree.Branch( 'Nation', AddressOf( staff, 'Nation' ), 'Nation/C' )
48 
49  # note that the branches Division and Nation cannot be on the first branch
50  fname = os.path.join(str(ROOT.gROOT.GetTutorialDir()), 'tree', 'cernstaff.dat')
51  for line in open(fname).readlines():
52  t = list(filter( lambda x: x, re.split( '\s+', line ) ) )
53  staff.Category = int(t[0]) # assign as integers
54  staff.Flag = int(t[1])
55  staff.Age = int(t[2])
56  staff.Service = int(t[3])
57  staff.Children = int(t[4])
58  staff.Grade = int(t[5])
59  staff.Step = int(t[6])
60  staff.Hrweek = int(t[7])
61  staff.Cost = int(t[8])
62  staff.Division = t[9] # assign as strings
63  staff.Nation = t[10]
64 
65  tree.Fill()
66 
67  tree.Print()
68  tree.Write()
69 
70 #### run fill function if invoked on CLI
71 if __name__ == '__main__':
72  staff()
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format...
Definition: TFile.h:46
Definition: staff.py:1
A TTree object has a header with a name and a title.
Definition: TTree.h:78