Python's CSV reader

Stephan usenet.filter at gmail.com
Sun Aug 7 22:23:19 EDT 2005


Andrew McLean wrote:

> You are welcome. One point. I think there have been at least two
> different interpretations of precisely what you task is.
>
> I had assumed that all the different "header" lines contained data for
> the same fields in the same order, and similarly that all the "detail"
> lines contained data for the same fields in the same order.

Indeed, you are correct.  Peter's version is interesting in its own
right, but not precisely what I had in mind.  However, from his example
I saw what I was missing: I didn't realize that you could reassign the
DictReader field names on the fly.  Here is a rudimentary example of my
working code and the data it can parse.

-------------------------------------
John|Smith
Beef|Potatos|Dinner Roll|Ice Cream
Susan|Jones
Chicken|Peas|Biscuits|Cake
Roger|Miller
Pork|Salad|Muffin|Cookies
-------------------------------------

import csv

HeaderFields = ["First Name", "Last Name"]
DetailFields = ["Entree", "Side Dish", "Starch", "Desert"]

reader = csv.DictReader(open("testdata.txt"), [], delimiter="|")

while True:
    try:
        # Read next "header" line (if there isn't one then exit the
loop)
        reader.fieldnames = HeaderFields
        header = reader.next()

        # Read the next "detail" line
        reader.fieldnames = DetailFields
        detail = reader.next()

        # Print the parsed data
        print '-' * 40
        print "Header (%d fields): %s" % (len(header), header)
        print "Detail (%d fields): %s" % (len(detail), detail)

    except StopIteration: break 

Regards,
-Stephan




More information about the Python-list mailing list