I have a text file. Each line of that file has either 6 fields or 7 fields.
-
If there are 7 fields in a line, i am making first 6 fields as a key and 7th field as the value for that key.
-
If there are 6 fields in a line, i am making first 5 fields as a key and 6th field as the value for that key.
I don’t know if posting the entire code is necessary or not, but for a clear picture, i am posting the entire code.
My code is pasted below:
ReqResRS = {}
with contextlib.nested(open(sys.argv[1],'r'), open(sys.argv[2], 'w')) as (inpf, outf):
lines = [l.split() for l in inpf if l.strip()]
for l in lines:
if(l[6]):
myKey = (l[0],l[1],l[2],l[3],l[4],l[5])
myValue = l[6]
if(myKey in ReqResRS):
diff = float(l[6])-float(ReqResRS[myKey]);
if(float(diff) < 0.000008):
ReqResRS[myKey] = myValue
else:
ReqResRS[myKey] = myValue
outf.write(l[0] + "\t" + l[1] + "\t" + l[2] + "\t" + l[3] + "\t" + l[4] + "\t" + l[5] + "\t" + l[6] + "\n")
else:
ReqResRS[myKey] = myValue
outf.write(l[0] + "\t" + l[1] + "\t" + l[2] + "\t" + l[3] + "\t" + l[4] + "\t" + l[5] + "\t" + l[6] + "\n")
else:
myKey = (l[0],l[1],l[2],l[3],l[4])
myValue = l[5]
if(myKey in ReqResRS):
diff = float(l[5])-float(ReqResRS[myKey]);
if(float(diff) < 0.000008):
ReqResRS[myKey] = myValue
else:
ReqResRS[myKey] = myValue
outf.write(l[0] + "\t" + l[1] + "\t" + l[2] + "\t" + l[3] + "\t" + l[4] + "\t" + l[5] + "\n")
else:
ReqResRS[myKey] = myValue
outf.write(l[0] + "\t" + l[1] + "\t" + l[2] + "\t" + l[3] + "\t" + l[4] + "\t" + l[5] + "\n")
fails if your array is to short.
Accessing a value that is not part of the array will allways result in an exception. Therefore you should check beforehand whether the array is long enough, like this: