summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Doc/library/csv.rst10
-rw-r--r--Lib/csv.py4
-rw-r--r--Lib/test/test_csv.py4
-rw-r--r--Misc/NEWS2
4 files changed, 20 insertions, 0 deletions
diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst
index 407efd0..c688da8 100644
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -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
diff --git a/Lib/csv.py b/Lib/csv.py
index 3db5dac..1df5062 100644
--- a/Lib/csv.py
+++ b/Lib/csv.py
@@ -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]
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index 196d18c..7eef4c0 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -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()
diff --git a/Misc/NEWS b/Misc/NEWS
index ff04b28..8b91de8 100644
--- 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
-----------------