]> granicus.if.org Git - python/commitdiff
Issue #20351: Add examples for csv.DictReader and csv.DictWriter.
authorBerker Peksag <berker.peksag@gmail.com>
Mon, 24 Nov 2014 21:46:30 +0000 (23:46 +0200)
committerBerker Peksag <berker.peksag@gmail.com>
Mon, 24 Nov 2014 21:46:30 +0000 (23:46 +0200)
Patch by Charles-Axel Dein.

Doc/library/csv.rst

index ccc9dc6e4cddc1f340165b0bb6211255626c1c57..9f7b58afa710e0977809b1e21793cbeb9c8cc64f 100644 (file)
@@ -158,6 +158,18 @@ The :mod:`csv` module defines the following classes:
    the optional *restval* parameter.  Any other optional or keyword arguments
    are passed to the underlying :class:`reader` instance.
 
+   A short usage example::
+
+       >>> import csv
+       >>> with open('names.csv') as csvfile:
+       ...     reader = csv.DictReader(csvfile)
+       ...     for row in reader:
+       ...         print(row['first_name'], row['last_name'])
+       ...
+       Baked Beans
+       Lovely Spam
+       Wonderful Spam
+
 
 .. class:: DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', \
                       dialect='excel', *args, **kwds)
@@ -180,6 +192,19 @@ The :mod:`csv` module defines the following classes:
    objects are not ordered, there is not enough information available to deduce
    the order in which the row should be written to the *csvfile*.
 
+   A short usage example::
+
+       import csv
+
+       with open('names.csv', 'w') as csvfile:
+           fieldnames = ['first_name', 'last_name']
+           writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
+
+           writer.writeheader()
+           writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
+           writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
+           writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
+
 
 .. class:: Dialect