How to write header row with csv.DictWriter?

后端 未结 3 740
攒了一身酷
攒了一身酷 2020-12-04 06:21

Assume I have a csv.DictReader object and I want to write it out as a CSV file. How can I do this?

I know that I can write the rows of data

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 07:01

    A few options:

    (1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.

    (2) The documentation mentions "the underlying writer instance" ... so just use it (example at the end).

    dw.writer.writerow(dw.fieldnames)
    

    (3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer

    Writing data:

    w.writerow([d[k] for k in fieldnames])
    

    or

    w.writerow([d.get(k, restval) for k in fieldnames])
    

    Instead of the extrasaction "functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:

    wrong_fields = [k for k in rowdict if k not in self.fieldnames]
    

    ============

    >>> f = open('csvtest.csv', 'wb')
    >>> import csv
    >>> fns = 'foo bar zot'.split()
    >>> dw = csv.DictWriter(f, fns, restval='Huh?')
    # dw.writefieldnames(fns) -- no such animal
    >>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\python26\lib\csv.py", line 144, in writerow
        return self.writer.writerow(self._dict_to_list(rowdict))
      File "C:\python26\lib\csv.py", line 141, in _dict_to_list
        return [rowdict.get(key, self.restval) for key in self.fieldnames]
    AttributeError: 'list' object has no attribute 'get'
    >>> dir(dw)
    ['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
    es', 'restval', 'writer', 'writerow', 'writerows']
    # eureka
    >>> dw.writer.writerow(dw.fieldnames)
    >>> dw.writerow({'foo':'oof'})
    >>> f.close()
    >>> open('csvtest.csv', 'rb').read()
    'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
    >>>
    

提交回复
热议问题