Scott wrote: > 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?
here's a relatively straightforward re solution that gives you a dictionary with the values for each line. import re for line in open("infile.txt"): d = {} for k, v1, v2 in re.findall("(\w+)=(?:(\w+)|'([^']*)')", line): d[k.lower()] = v1 or v2 print d (the pattern looks for alphanumeric characters (k) followed by an equal sign followed by either a number of alphanumeric characters (v1), or text inside single quotes (v2). either v1 or v2 will be set) getting from dictionary to file is left as an exercise to the reader. </F> -- http://mail.python.org/mailman/listinfo/python-list