Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
mergeFiles.py
Go to the documentation of this file.
1# \file
2# \ingroup tutorial_io
3# \notebook -nodraw
4# Illustrates how to merge two files using TFileMerger from Python.
5# \author Giacomo Parolini
6
7import ROOT
8import os
9import random
10
11# abridged from hsimple.py
12def CreateInputFile(fname):
13 with ROOT.TFile.Open( fname, "RECREATE", "Demo ROOT file with histograms" ) as hfile:
14 # Create some histograms, a profile histogram and an ntuple
15 hpx = ROOT.TH1F( "hpx", "This is the px distribution", 100, -4, 4 )
16 hpxpy = ROOT.TH2F( "hpxpy", "py vs px", 40, -4, 4, 40, -4, 4 )
17 hprof = ROOT.TProfile( "hprof", "Profile of pz versus px", 100, -4, 4, 0, 20 )
18 ntuple = ROOT.TNtuple( "ntuple", "Demo ntuple", "px:py:pz:random:i" )
19
20 # Fill histograms randomly.
21 for i in range( 2000 ):
22 px = random.randrange(0, 1)
23 py = random.randrange(0, 1)
24 pz = px*px + py*py
25 r = random.randrange(0, 1)
26
27 # Fill histograms.
28 hpx.Fill( px )
29 hpxpy.Fill( px, py )
30 hprof.Fill( px, pz )
31 ntuple.Fill( px, py, pz, r, i )
32 hfile.Write()
33
34
35def MergeFiles(files_to_cleanup, nfiles):
36 # NOTE: when the TFileMerger is used in a `with` statement, it will automatically
37 # close its output file when going out of scope.
38 with ROOT.TFileMerger(False) as fm:
39 fm.OutputFile("merged.root")
40 files_to_cleanup.append(fm.GetOutputFile().GetName())
41 for i in range(0, nfiles):
42 fm.AddFile(f"tomerge{i}.root")
43
44 # New merging flags must be bitwise OR-ed on top of the default ones.
45 # Here, as an example, we are doing an incremental merging, meaning we want to merge the new
46 # files with the current content of the output file.
47 # See TFileMerger docs for all the flags available:
48 # https://root.cern/doc/master/classTFileMerger.html#a8ea43dc0722ce413c7332584d8c3ef0f
49 mode = ROOT.TFileMerger.kAll | ROOT.TFileMerger.kIncremental
50 fm.PartialMerge(mode)
51 fm.Reset()
52
53
54if __name__ == '__main__':
55 nfiles = 2
56 files_to_cleanup = []
57 try:
58 # Create the files to be merged
59 for i in range(0, nfiles):
60 fname = f"tomerge{i}.root"
61 CreateInputFile(fname)
62 files_to_cleanup.append(fname)
63
64 MergeFiles(files_to_cleanup, nfiles)
65
66 finally:
67 # Cleanup initial files
68 for filename in files_to_cleanup:
69 os.remove(filename)
70