I’m reading positional records from a text file, for examle, it looks like this:
AB ATEA 000401550
Each record is assigned a specific number of characters, for example:
Code: AB (characters from 0 - 2)
Name: ATEA (characters from 3 - 7)
Value1: 00040 (characters from 8 - 13)
Value2: 1550 (characters from 13 - 16)
I have no problem parsing this using a loop and a list of tuples as the record keys & character locations, and storing these records in a dictionary as such:
alist = [('Code',0,2),('Name',3,7),('Value1',8,13),('Value2',13,16)]
adict = {}
for x in afile:
for a, b, c in alist:
adict[a] = x[b:c]
Now, the problem is that the dictionary values must be formatted using a specific data type & specific number of decimals, for example:
Code = X i.e. string
Name = X i.e. string
Value1 = 9V9(4) i.e. float with 4 decimals, i.e. 0.0040
Value2 = 9(2)V9(2) i.e. float with 2 decimals, i.e. 15.50
So, I figured I can build a function which takes the record name and record value as inputs, then, inside this function lives a dictionary which contains the record value’s formatting, for example:
def converter(name, value):
adict = {'Code':'%s' % value,
'Name':'%s' % value,
'Value1':float('%s.%s' % (value[:1],value[1:])),
'Value2':float('%s.%s' % (value[:2],value[2:]))}
return adict[name]
The problem is that when i run the parse loop as follows:
alist = [('Code',0,2),('Name',3,7),('Value1',8,13),('Value2',13,16)]
adict = {}
for x in afile:
for a, b, c in alist:
adict[a] = converter(a,x[b:c])
Python throws a ValueError because the value input in the function is fed through all items in the dictionary at runtime, therefore, when ‘AB’ is fed onto the “float()” the dictionary creation stops and python throws the error.
You can specify a converter for each item:
See it working online: ideone