summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorR. David Murray <rdmurray@bitdance.com>2010-02-23 22:57:58 (GMT)
committerR. David Murray <rdmurray@bitdance.com>2010-02-23 22:57:58 (GMT)
commitbe0698b1ad096d8bd6564fa06486f2fcea47cac9 (patch)
tree892dc44548a60c7a3d457b8f44e9cd4cd35024b3 /Lib
parent5117b0b0dc9c28d158c9f46bca0965ee00ac98e7 (diff)
downloadcpython-be0698b1ad096d8bd6564fa06486f2fcea47cac9.zip
cpython-be0698b1ad096d8bd6564fa06486f2fcea47cac9.tar.gz
cpython-be0698b1ad096d8bd6564fa06486f2fcea47cac9.tar.bz2
Merged revisions 78384 via svnmerge from
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. ........
Diffstat (limited to 'Lib')
-rw-r--r--Lib/csv.py4
-rw-r--r--Lib/test/test_csv.py4
2 files changed, 8 insertions, 0 deletions
diff --git a/Lib/csv.py b/Lib/csv.py
index 59ec372..5ae5a73 100644
--- a/Lib/csv.py
+++ b/Lib/csv.py
@@ -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]
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index 29e54f7..2c4b783 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -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):