Q:

Parsing a generic data file in python

I have a data file that is pretty simple in the format of title : data.
For example (real file is the same but with more data):
Images : 50
Total cells : 532
Viable cells : 512
Nonviable cells : 20

Right now to parse this I have the following code for every data piece I want:
if data[1][:12] == "Total Cells :":
    result.append(data[1][13:-1])

This feels like a really dirty solution though. What would be a more clean way to solve this problem?

A:

You can simply split the line on ' : ':
key, value = data[1].split(' : ', 1)

Now you have the two elements of the line separated into two variables. You may want to strip these of extraneous whitespace:
key, value = map(str.strip, data[1].split(':', 1))

Demo:
>>> map(str.strip, 'Images : 50'.split(':'))
['Images', '50']
>>> map(str.strip, 'Total cells : 532'.split(':'))
['Total cells', '532']

A:

If you want this data file in a nice dictionary, you can do the following:
d = {}
for line in data:
    key, value = line.split(':')
    d[key] = value

printing out d will return:
{'Images': 50, 'Total cells': 532, 'Viable cells': 512, 'Nonviable cells': 20}

This assumes none of your "keys" or "values" have : in them.
You can then access any of the elements (i.e. "Total Cells") like so:
print d['Total cells']

