]> granicus.if.org Git - python/commitdiff
Merged revisions 78384 via svnmerge from
authorR. David Murray <rdmurray@bitdance.com>
Tue, 23 Feb 2010 22:57:58 +0000 (22:57 +0000)
committerR. David Murray <rdmurray@bitdance.com>
Tue, 23 Feb 2010 22:57:58 +0000 (22:57 +0000)
svn+ssh://pythondev@svn.python.org/python/trunk

........
  r78384 | dirkjan.ochtman | 2010-02-23 16:09:52 -0500 (Tue, 23 Feb 2010) | 4 lines

  Fix #1537721: add writeheader() method to csv.DictWriter.

  Reviewed by skip.montanaro and thomas.wouters.
........

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

index 510d35a4000f4e76d7a627444e2901422a0e057c..502d9349dbf3cb16a7f28ca802150135fb690ed6 100644 (file)
@@ -392,6 +392,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 59ec372ec0a35c43f1a5c0ab4a1a7d41ff93c761..5ae5a730468ff6bc8a4bf4047973c56277f1900c 100644 (file)
@@ -127,6 +127,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 29e54f789a08b3693df4dad50580f440f57dd24f..2c4b78305dfd75d7f9851bf5fb89e86447ce9874 100644 (file)
@@ -535,8 +535,12 @@ class TestDictFields(unittest.TestCase):
     def test_write_simple_dict(self):
         with TemporaryFile("w+", newline='') as fileobj:
             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")
 
     def test_write_no_fields(self):
index 6abe1e2c93e2f584db2ec2f5af368db959ebdba0..666139f104fc4411052ab89edcf1dcf980227698 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -254,6 +254,8 @@ C-API
 Library
 -------
 
+- Issue #1537721: Add a writeheader() method to csv.DictWriter.
+
 - Issue #7959: ctypes callback functions are now registered correctly
   with the cylce garbage collector.