mirror of
https://github.com/python/cpython.git
synced 2025-08-03 16:39:00 +00:00
Fix #1537721: add writeheader() method to csv.DictWriter.
Reviewed by skip.montanaro and thomas.wouters.
This commit is contained in:
parent
92bd059c67
commit
8614817875
4 changed files with 20 additions and 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]
|
||||
|
|
|
@ -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()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue