Python CSV writer confusion.

googleboy mynews44 at
Thu Sep 15 12:56:27 CEST 2005

Hi.  I am trying to write out a csv file with | instead of comma,
because I have a field that may have many commas in it.  I read in a
csv file, sort it,  and want to write it out again.

I read the example that says:

import csv
writer = csv.writer(open("some.csv", "wb"))

The "someiterable" is what is confusing me.

class Image(object):
    def __init__(self, title, date, genre, data, value, filename):
        params = locals()
        del params['self']
    def __repr__(self):
        all_items = self.__dict__.items()
        return '%s,%s,%s,%s,%s, %s' % (self.title,,
self.genre,, self.value, self.filename)

def read_images(filename):
    csv_file = open(filename, "rb")
    reader = csv.reader(csv_file, dialect='excel', delimiter='|')
    images = [Image(*[field.strip() for field in row]) for row in
    return books

def sort_images(filename, *attr_names):
    csv_file = open(filename, "rb")
    reader = csv.reader(csv_file, dialect='excel', delimiter='|')

if __name__ == '__main__':
    images = read_images(r"D:\path\to\imagespipe.csv")

    def get_key(*attr_names):
        def key(image):
            return [getattr(image, name) for name in attr_names]
        return key

    images.sort(key = get_key("filename"))

    t = open(r'D:\path\to\filename_sort1.csv', 'w')

    for image in images:
        print book
        #t.write('%s\n' % book)     %Before I needed | delimited, this
        #csv.writer(t, dialect='excel', delimiter='|')
        output = csv.writer(t, dialect='excel', delimiter='|')


This returns an error that says "Error: sequence expected"

My understanding of this is that I am creating a list of lists and I am
iterating over it (for image in images),  and that image is a list, and
is therefore iterable...?

I am a bit new at this, and would greatly appreciate any assistance.



More information about the Python-list mailing list