diff options
author | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2010-02-23 21:09:52 (GMT) |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2010-02-23 21:09:52 (GMT) |
commit | 86148178754c5403067df8234df2f9bb85c733a7 (patch) | |
tree | e6a839bc428d76fe5b86e58c4460d5d6a00e06aa /Lib | |
parent | 92bd059c678e85df3c6fff24dbf4b8b7b27b61bd (diff) | |
download | cpython-86148178754c5403067df8234df2f9bb85c733a7.zip cpython-86148178754c5403067df8234df2f9bb85c733a7.tar.gz cpython-86148178754c5403067df8234df2f9bb85c733a7.tar.bz2 |
Fix #1537721: add writeheader() method to csv.DictWriter.
Reviewed by skip.montanaro and thomas.wouters.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/csv.py | 4 | ||||
-rw-r--r-- | Lib/test/test_csv.py | 4 |
2 files changed, 8 insertions, 0 deletions
@@ -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() |