]> granicus.if.org Git - python/commitdiff
Fix #1537721: add writeheader() method to csv.DictWriter.
authorDirkjan Ochtman <dirkjan@ochtman.nl>
Tue, 23 Feb 2010 21:09:52 +0000 (21:09 +0000)
committerDirkjan Ochtman <dirkjan@ochtman.nl>
Tue, 23 Feb 2010 21:09:52 +0000 (21:09 +0000)
Reviewed by skip.montanaro and thomas.wouters.

Doc/library/csv.rst
Lib/csv.py
Lib/test/test_csv.py
Misc/NEWS

index 407efd0233ac886e84ef4f1b8cc81dab5c31a942..c688da89ccaa7c8ff8c260af3f04a24cc036c363 100644 (file)
@@ -424,6 +424,16 @@ Writer objects have the following public attribute:
    A read-only description of the dialect in use by the writer.
 
 
+DictWriter objects have the following public method:
+
+
+.. method:: DictWriter.writeheader()
+
+   Write a row with the field names (as specified in the constructor).
+
+   .. versionadded:: 2.7
+
+
 .. _csv-examples:
 
 Examples
index 3db5dac5db666380c03d77473fa05efcbbb075bf..1df506230fd029aaa8f6415bfb2ab2fb84119de7 100644 (file)
@@ -132,6 +132,10 @@ class DictWriter:
         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 196d18c2a762677a90e781577e5b5f7ef25886dc..7eef4c090b971477368d2a3471aecc41c8c7d9fb 100644 (file)
@@ -598,8 +598,12 @@ class TestDictFields(unittest.TestCase):
         fileobj = os.fdopen(fd, "w+b")
         try:
             writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
+            writer.writeheader()
+            fileobj.seek(0)
+            self.assertEqual(fileobj.readline(), "f1,f2,f3\r\n")
             writer.writerow({"f1": 10, "f3": "abc"})
             fileobj.seek(0)
+            fileobj.readline() # header
             self.assertEqual(fileobj.read(), "10,,abc\r\n")
         finally:
             fileobj.close()
index ff04b289d9c788115878a1bff51c423adc19ea9e..8b91de8345d638223a0618c2b613e114cbcff403 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -53,6 +53,8 @@ Library
 
 - Issue #5801: removed spurious empty lines in wsgiref.
 
+- Issue #1537721: Add a writeheader() method to csv.DictWriter.
+
 Extension Modules
 -----------------