[Python-checkins] r78384 - in python/trunk: Doc/library/csv.rst Lib/csv.py Lib/test/test_csv.py Misc/NEWS

dirkjan.ochtman python-checkins at python.org
Tue Feb 23 22:09:52 CET 2010


Author: dirkjan.ochtman
Date: Tue Feb 23 22:09:52 2010
New Revision: 78384

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

Reviewed by skip.montanaro and thomas.wouters.


Modified:
   python/trunk/Doc/library/csv.rst
   python/trunk/Lib/csv.py
   python/trunk/Lib/test/test_csv.py
   python/trunk/Misc/NEWS

Modified: python/trunk/Doc/library/csv.rst
==============================================================================
--- python/trunk/Doc/library/csv.rst	(original)
+++ python/trunk/Doc/library/csv.rst	Tue Feb 23 22:09:52 2010
@@ -424,6 +424,16 @@
    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

Modified: python/trunk/Lib/csv.py
==============================================================================
--- python/trunk/Lib/csv.py	(original)
+++ python/trunk/Lib/csv.py	Tue Feb 23 22:09:52 2010
@@ -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]

Modified: python/trunk/Lib/test/test_csv.py
==============================================================================
--- python/trunk/Lib/test/test_csv.py	(original)
+++ python/trunk/Lib/test/test_csv.py	Tue Feb 23 22:09:52 2010
@@ -598,8 +598,12 @@
         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()

Modified: python/trunk/Misc/NEWS
==============================================================================
--- python/trunk/Misc/NEWS	(original)
+++ python/trunk/Misc/NEWS	Tue Feb 23 22:09:52 2010
@@ -53,6 +53,8 @@
 
 - Issue #5801: removed spurious empty lines in wsgiref.
 
+- Issue #1537721: Add a writeheader() method to csv.DictWriter.
+
 Extension Modules
 -----------------
 


More information about the Python-checkins mailing list