Skip to content Skip to sidebar Skip to footer

Specifying Formatting For Csv.writer In Python

I am using csv.DictWriter to output csv files from a set of dictionaries. I use the following function: def dictlist2file(dictrows, filename, fieldnames, delimiter='\t',

Solution 1:

class TypedWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which uses "fieldformats" to format fields.
    """

    def __init__(self, f, fieldnames, fieldformats, **kwds):
        self.writer = csv.DictWriter(f, fieldnames, **kwds)
        self.formats = fieldformats

    def writerow(self, row):
        self.writer.writerow(dict((k, self.formats[k] % v) 
                                  for k, v in row.iteritems()))

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

Not tested.


Post a Comment for "Specifying Formatting For Csv.writer In Python"