listfile="files.txt" #list of files to be mreged num_ev=15 # number of events per merged file, needs to be more than events in each file outfname="Events_merged" # appended with "_i.hepmc first=True counter_ev=0 counter_evtot=0 counter_file=0 header=[] outfile=None with open(listfile) as inputlist: for infile in inputlist: with open(infile.rstrip()) as hepmc: for line in hepmc: #ignore empty lines if not line.strip(): continue #extract the header from the first file if line.startswith("HepMC::Version"): if first: header.append(line) continue if line.startswith("HepMC::IO_GenEvent-START_EVENT_LISTING"): if first: header.append(line) first = False continue #end-of-file doesn't matter if line.startswith("HepMC::IO_GenEvent-END_EVENT_LISTING"): continue if line.startswith("E"): counter_ev=counter_ev+1 counter_evtot=counter_evtot+1 #is this the first event for a new file? if counter_ev > num_ev: outfile.write("HepMC::IO_GenEvent-END_EVENT_LISTING") outfile.close() outfile=None counter_ev=1 if outfile==None: print "Opening new file "+outfname+"_"+str(counter_file)+".hepmc for event "+str(counter_evtot) outfile=open(outfname+"_"+str(counter_file)+".hepmc","w") for entry in header: outfile.write(entry) #print entry counter_file=counter_file+1 adjustedline = line.split() #print line #print adjustedline adjustedline[1]=str(counter_ev) outfile.write(' '.join(adjustedline)+"\n") continue outfile.write(line) outfile.write("HepMC::IO_GenEvent-END_EVENT_LISTING") outfile.close() print "merged "+ str(counter_evtot) + " evnets into "+ str(counter_file) + " Files"