You are likely to have empty lines in your data file, and splitting such line will not return list with enough items present.
In your loop you shall call continue
if you meet an empty line.
Another hint is to call split
with 2nd argument telling, how many splits shall be applied. This shall allow getting the final JSON part and you may use json.loads
on it to get the content
If I modify your data to reflect your statement about having JSON data at the end,
014-05-14,12:16:26,subject,{"MSGTYPE":"Personal", "NAME":"Fred", "ADDRESS":"Flat1", "AGE": 92, "GENDER":"M"}
2014-05-15,14:36:26,subject,{"MSGTYPE":"Personal", "NAME":"George", "ADDRESS":"Flat2", "AGE": -20, "GENDER":"M"}
2014-05-13,16:49:26,subject,{"MSGTYPE":"Personal", "NAME":"Ringo", "ADDRESS":"Flat3", "AGE": -36, "GENDER":"M"}
2014-05-12,14:45:26,subject,{"MSGTYPE":"Personal", "NAME":"Brian", "ADDRESS":"Flat4", "AGE": -85, "GENDER":"M"}
2014-05-11,12:43:26,subject,{"MSGTYPE":"Personal", "NAME":"Paul", "ADDRESS":"Flat5", "AGE": -33, "GENDER":"M"}
it would work like this:
import json
fname = "data.txt"
with open(fname) as f:
for line in f:
line = line.strip()
if len(line) == 0:
continue
if line.startswith('**Records**'):
continue
valuesArray = line.split(',', 3)
y, d = valuesArray[:2]
print '1: {y}'.format(y=y)
print '2: {d}'.format(d=d)
# bonus, read the json data
print valuesArray[3]
jsdata = json.loads(valuesArray[3])
print "jsdata", jsdata