#combine (numerically add entries) ASCII files line-wise #assumes lines of float values eperated by white space(s) #lines can be flagged with -ig to have them ignored and #just copied once to the output file #author: Felix Boehmer import glob, sys, os options = ["-f","-of","-clname","-ig","-trname","-ml","-mh","-v","-gf","-resname"] opts = set(options) def getArgsToNextOpt(stringlist, index) : id = index+1 args = [] while(id < len(stringlist)): if stringlist[id] in options: return args args.append(stringlist[id]) id+=1 return args ignorelist = [] outfilegiven = 0 for iarg in range(len(sys.argv)) : arg = sys.argv[iarg] if arg == "-f": files = getArgsToNextOpt(sys.argv,iarg) if arg == "-ig" : igs = getArgsToNextOpt(sys.argv,iarg) for i in igs: ignorelist.append(int(i)) if arg == "-of": outfiles = getArgsToNextOpt(sys.argv,iarg) if len(outfiles) > 1 : print "ERROR: Invalid output file!" print outfile exit outfile = outfiles[0] outfilegiven = 1 if not outfilegiven: print "ERROR: No output file was given!" exit for f in files: print f print data = {} #line number -> line content numdata = {} #line number -> list of floats if len(ignorelist) > 0: sys.stdout.write("Ignoring (copying) lines ") for i in ignorelist: sys.stdout.write(str(i)+", ") print fcounter = 0 for f in files: ifile = open(f, "r") lcounter = 0 for l in ifile: if lcounter in ignorelist: if fcounter == 0: #don't process, just copy (once) data[lcounter] = l lcounter+=1 continue #convert input string to list of strings: linelist = l.split() #assuming whitespaces are the delimiter if lcounter not in numdata.keys(): numdata[lcounter] = [] for d in linelist: (numdata[lcounter]).append(float(d)) else : #this line already exists -> check consistency and add if len(linelist) != len(numdata[lcounter]) : print "ERROR!!!! DATA FILES INCONSISTENT!" exit else : ncounter = 0 for d in linelist: (numdata[lcounter])[ncounter] += float(d) ncounter+=1 lcounter+=1 ifile.close() fcounter+=1 for line, numlist in numdata.iteritems(): ncount = 0 outline = "" for d in numlist: if ncount == 0: outline = str(d) else: outline+=" " outline+=str(d) #check for consistency if line in data.keys(): print "ERROR: Something is wrong. Line already existing in output data!" exit data[line] = outline print "Writing new file:",outfile out = open(outfile,"w") for line, datline in data.iteritems(): #print line, datline out.write(datline) out.write("\n") out.close()