Catalina Scott A Contr AFCA/EVEO schrieb: > I have a file with lines in the following format. > > pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon' > Pie=peach,quantity=2,ingredients='peaches,powdered sugar' > Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar' > > I would like to pull out some of the values and write them to a csv > file. > > For line in filea > pie = regex > quantity = regex > cooked = regex > ingredients = regex > fileb.write (quantity,pie,cooked,ingredients) > > How can I retreive the values and assign them to a name? > > Thank you > Scott
Try this: import re import StringIO filea_string = """pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon' pie=peach,quantity=2,ingredients='peaches,powdered sugar' pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar' """ FIELDS = ("pie", "quantity", "cooked", "ingredients", "price") field_regexes = {} for field in FIELDS: field_regexes[field] = re.compile("%s=([^,\n]*)" % field) for line in StringIO.StringIO(filea_string): field_values = {} for field in FIELDS: match_object = field_regexes[field].search(line) if match_object is not None: field_values[field] = match_object.group(1) print field_values #fileb.write (quantity,pie,cooked,ingredients) Bye, Dennis -- http://mail.python.org/mailman/listinfo/python-list