[issue1537721] csv module: add header row to DictWriter
djc
report at bugs.python.org
Mon Dec 7 19:22:54 CET 2009
djc <dirkjan at ochtman.nl> added the comment:
I'd like to commit this, but it would be nice to get a review first:
Index: Lib/csv.py
===================================================================
--- Lib/csv.py (revision 76697)
+++ Lib/csv.py (working copy)
@@ -132,6 +132,10 @@
self.extrasaction = extrasaction
self.writer = writer(f, dialect, *args, **kwds)
+ def writeheader(self):
+ header = dict(zip(self.fieldnames, self.fieldnames))
+ self.writerow(header)
+
def _dict_to_list(self, rowdict):
if self.extrasaction == "raise":
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
Index: Lib/test/test_csv.py
===================================================================
--- Lib/test/test_csv.py (revision 76697)
+++ Lib/test/test_csv.py (working copy)
@@ -598,8 +598,10 @@
fileobj = os.fdopen(fd, "w+b")
try:
writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2",
"f3"])
+ writer.writeheader()
writer.writerow({"f1": 10, "f3": "abc"})
fileobj.seek(0)
+ self.assertEqual(fileobj.readline(), "f1,f2,f3\r\n")
self.assertEqual(fileobj.read(), "10,,abc\r\n")
finally:
fileobj.close()
(I think I have commit privileges already.)
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue1537721>
_______________________________________
More information about the Python-bugs-list
mailing list