Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6cecf68

Browse files
committed
Issue #20351: Add examples for csv.DictReader and csv.DictWriter.
Patch by Charles-Axel Dein.
2 parents da8cef4 + c8c64e3 commit 6cecf68

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

Doc/library/csv.rst

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,18 @@ The :mod:`csv` module defines the following classes:
159159
the optional *restval* parameter. Any other optional or keyword arguments
160160
are passed to the underlying :class:`reader` instance.
161161

162+
A short usage example::
163+
164+
>>> import csv
165+
>>> with open('names.csv') as csvfile:
166+
... reader = csv.DictReader(csvfile)
167+
... for row in reader:
168+
... print(row['first_name'], row['last_name'])
169+
...
170+
Baked Beans
171+
Lovely Spam
172+
Wonderful Spam
173+
162174

163175
.. class:: DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', \
164176
dialect='excel', *args, **kwds)
@@ -181,6 +193,19 @@ The :mod:`csv` module defines the following classes:
181193
objects are not ordered, there is not enough information available to deduce
182194
the order in which the row should be written to the *csvfile*.
183195

196+
A short usage example::
197+
198+
import csv
199+
200+
with open('names.csv', 'w') as csvfile:
201+
fieldnames = ['first_name', 'last_name']
202+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
203+
204+
writer.writeheader()
205+
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
206+
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
207+
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
208+
184209

185210
.. class:: Dialect
186211

0 commit comments

Comments
 (0)