rest25/library/csv.rst => rest262/library/csv.rst
40   This version of the :mod:`csv` module doesn't support Unicode input.  Also,
41   there are currently some issues regarding ASCII NUL characters.  Accordingly,
42   all input should be UTF-8 or printable ASCII to be safe; see the examples in
43   section :ref:`csv-examples`. These restrictions will be removed in the future.
44
45
46.. seealso::
47
n48-   .. % \seemodule{array}{Arrays of uniformly types numeric values.}
49- 
50   :pep:`305` - CSV File API
51      The Python Enhancement Proposal which proposed this addition to Python.
52
53
54.. _csv-contents:
55
56Module Contents
57---------------
58
59The :mod:`csv` module defines the following functions:
60
61
n62-.. function:: reader(csvfile[, dialect=``'excel'``][, fmtparam])
n60+.. function:: reader(csvfile[, dialect='excel'][, fmtparam])
63
64   Return a reader object which will iterate over lines in the given *csvfile*.
n65-   *csvfile* can be any object which supports the iterator protocol and returns a
n63+   *csvfile* can be any object which supports the :term:`iterator` protocol and returns a
66   string each time its :meth:`next` method is called --- file objects and list
67   objects are both suitable.   If *csvfile* is a file object, it must be opened
68   with the 'b' flag on platforms where that makes a difference.  An optional
69   *dialect* parameter can be given which is used to define a set of parameters
70   specific to a particular CSV dialect.  It may be an instance of a subclass of
71   the :class:`Dialect` class or one of the strings returned by the
72   :func:`list_dialects` function.  The other optional *fmtparam* keyword arguments
73   can be given to override individual formatting parameters in the current
n74-   dialect.  For more information about the dialect and formatting parameters, see
n72+   dialect.  For full details about the dialect and formatting parameters, see
75-   section :ref:`csv-fmt-params`, "Dialects and Formatting Parameters" for details
73+   section :ref:`csv-fmt-params`.
76-   of these parameters.
77
78   All data read are returned as strings.  No automatic data type conversion is
79   performed.
n77+ 
78+   A short usage example::
79+ 
80+      >>> import csv
81+      >>> spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|')
82+      >>> for row in spamReader:
83+      ...     print ', '.join(row)
84+      Spam, Spam, Spam, Spam, Spam, Baked Beans
85+      Spam, Lovely Spam, Wonderful Spam
80
81   .. versionchanged:: 2.5
82      The parser is now stricter with respect to multi-line quoted fields. Previously,
83      if a line ended within a quoted field without a terminating newline character, a
84      newline would be inserted into the returned field. This behavior caused problems
85      when reading files which contained carriage return characters within fields.
86      The behavior was changed to return the field without inserting newlines. As a
87      consequence, if newlines embedded within fields are important, the input should
88      be split into lines in a manner which preserves the newline characters.
89
90
n91-.. function:: writer(csvfile[, dialect=``'excel'``][, fmtparam])
n97+.. function:: writer(csvfile[, dialect='excel'][, fmtparam])
92
93   Return a writer object responsible for converting the user's data into delimited
94   strings on the given file-like object.  *csvfile* can be any object with a
95   :func:`write` method.  If *csvfile* is a file object, it must be opened with the
96   'b' flag on platforms where that makes a difference.  An optional *dialect*
97   parameter can be given which is used to define a set of parameters specific to a
98   particular CSV dialect.  It may be an instance of a subclass of the
99   :class:`Dialect` class or one of the strings returned by the
100   :func:`list_dialects` function.  The other optional *fmtparam* keyword arguments
101   can be given to override individual formatting parameters in the current
n102-   dialect.  For more information about the dialect and formatting parameters, see
n108+   dialect.  For full details about the dialect and formatting parameters, see
103-   section :ref:`csv-fmt-params`, "Dialects and Formatting Parameters" for details
109+   section :ref:`csv-fmt-params`. To make it
104-   of these parameters.  To make it as easy as possible to interface with modules
110+   as easy as possible to interface with modules which implement the DB API, the
105-   which implement the DB API, the value :const:`None` is written as the empty
111+   value :const:`None` is written as the empty string.  While this isn't a
106-   string.  While this isn't a reversible transformation, it makes it easier to
112+   reversible transformation, it makes it easier to dump SQL NULL data values to
107-   dump SQL NULL data values to CSV files without preprocessing the data returned
113+   CSV files without preprocessing the data returned from a ``cursor.fetch*`` call.
108-   from a ``cursor.fetch*`` call.  All other non-string data are stringified with
114+   All other non-string data are stringified with :func:`str` before being written.
109-   :func:`str` before being written.
115+ 
116+   A short usage example::
117+ 
118+      >>> import csv
119+      >>> spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ',
120+      ...                         quotechar='|', quoting=QUOTE_MINIMAL)
121+      >>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
122+      >>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
110
111
112.. function:: register_dialect(name[, dialect][, fmtparam])
113
114   Associate *dialect* with *name*.  *name* must be a string or Unicode object. The
115   dialect can be specified either by passing a sub-class of :class:`Dialect`, or
116   by *fmtparam* keyword arguments, or both, with keyword arguments overriding
n117-   parameters of the dialect. For more information about the dialect and formatting
n130+   parameters of the dialect. For full details about the dialect and formatting
118-   parameters, see section :ref:`csv-fmt-params`, "Dialects and Formatting
131+   parameters, see section :ref:`csv-fmt-params`.
119-   Parameters" for details of these parameters.
120
121
122.. function:: unregister_dialect(name)
123
124   Delete the dialect associated with *name* from the dialect registry.  An
125   :exc:`Error` is raised if *name* is not a registered dialect name.
126
127
128.. function:: get_dialect(name)
129
130   Return the dialect associated with *name*.  An :exc:`Error` is raised if *name*
131   is not a registered dialect name.
132
n145+   .. versionchanged:: 2.5
146+      This function now returns an immutable :class:`Dialect`.  Previously an
147+      instance of the requested dialect was returned.  Users could modify the
148+      underlying class, changing the behavior of active readers and writers.
133
134.. function:: list_dialects()
135
136   Return the names of all registered dialects.
137
138
139.. function:: field_size_limit([new_limit])
140
141   Returns the current maximum field size allowed by the parser. If *new_limit* is
142   given, this becomes the new limit.
143
144   .. versionadded:: 2.5
145
146The :mod:`csv` module defines the following classes:
147
148
n149-.. class:: DictReader(csvfile[, fieldnames=:const:`None`,[, restkey=:const:`None`[, restval=:const:`None`[, dialect=``'excel'``[, *args, **kwds]]]]])
n165+.. class:: DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])
150
151   Create an object which operates like a regular reader but maps the information
152   read into a dict whose keys are given by the optional  *fieldnames* parameter.
153   If the *fieldnames* parameter is omitted, the values in the first row of the
154   *csvfile* will be used as the fieldnames. If the row read has fewer fields than
155   the fieldnames sequence, the value of *restval* will be used as the default
156   value.  If the row read has more fields than the fieldnames sequence, the
157   remaining data is added as a sequence keyed by the value of *restkey*.  If the
158   row read has fewer fields than the fieldnames sequence, the remaining keys take
159   the value of the optional *restval* parameter.  Any other optional or keyword
160   arguments are passed to the underlying :class:`reader` instance.
161
162
n163-.. class:: DictWriter(csvfile, fieldnames[, restval=""[, extrasaction=``'raise'``[, dialect=``'excel'``[, *args, **kwds]]]])
n179+.. class:: DictWriter(csvfile, fieldnames[, restval=''[, extrasaction='raise'[, dialect='excel'[, *args, **kwds]]]])
164
165   Create an object which operates like a regular writer but maps dictionaries onto
166   output rows.  The *fieldnames* parameter identifies the order in which values in
167   the dictionary passed to the :meth:`writerow` method are written to the
168   *csvfile*.  The optional *restval* parameter specifies the value to be written
169   if the dictionary is missing a key in *fieldnames*.  If the dictionary passed to
170   the :meth:`writerow` method contains a key not found in *fieldnames*, the
171   optional *extrasaction* parameter indicates what action to take.  If it is set
184   The :class:`Dialect` class is a container class relied on primarily for its
185   attributes, which are used to define the parameters for a specific
186   :class:`reader` or :class:`writer` instance.
187
188
189.. class:: excel()
190
191   The :class:`excel` class defines the usual properties of an Excel-generated CSV
n192-   file.
n208+   file.  It is registered with the dialect name ``'excel'``.
193
194
195.. class:: excel_tab()
196
197   The :class:`excel_tab` class defines the usual properties of an Excel-generated
n198-   TAB-delimited file.
n214+   TAB-delimited file.  It is registered with the dialect name ``'excel-tab'``.
199
200
201.. class:: Sniffer()
202
203   The :class:`Sniffer` class is used to deduce the format of a CSV file.
204
n205-The :class:`Sniffer` class provides two methods:
n221+   The :class:`Sniffer` class provides two methods:
206
n207- 
208-.. method:: Sniffer.sniff(sample[,delimiters=None])
223+   .. method:: sniff(sample[, delimiters=None])
209
n210-   Analyze the given *sample* and return a :class:`Dialect` subclass reflecting the
n225+      Analyze the given *sample* and return a :class:`Dialect` subclass
211-   parameters found.  If the optional *delimiters* parameter is given, it is
226+      reflecting the parameters found.  If the optional *delimiters* parameter
212-   interpreted as a string containing possible valid delimiter characters.
227+      is given, it is interpreted as a string containing possible valid
228+      delimiter characters.
213
214
n215-.. method:: Sniffer.has_header(sample)
n231+   .. method:: has_header(sample)
216
n217-   Analyze the sample text (presumed to be in CSV format) and return :const:`True`
n233+      Analyze the sample text (presumed to be in CSV format) and return
218-   if the first row appears to be a series of column headers.
234+      :const:`True` if the first row appears to be a series of column headers.
235+ 
236+An example for :class:`Sniffer` use::
237+ 
238+   csvfile = open("example.csv")
239+   dialect = csv.Sniffer().sniff(csvfile.read(1024))
240+   csvfile.seek(0)
241+   reader = csv.reader(csvfile, dialect)
242+   # ... process CSV file contents here ...
243+ 
219
220The :mod:`csv` module defines the following constants:
n221- 
222
223.. data:: QUOTE_ALL
224
225   Instructs :class:`writer` objects to quote all fields.
226
227
228.. data:: QUOTE_MINIMAL
229
332
333Reader Objects
334--------------
335
336Reader objects (:class:`DictReader` instances and objects returned by the
337:func:`reader` function) have the following public methods:
338
339
n340-.. method:: csv reader.next()
n364+.. method:: csvreader.next()
341
342   Return the next row of the reader's iterable object as a list, parsed according
343   to the current dialect.
344
345Reader objects have the following public attributes:
346
347
n348-.. attribute:: csv reader.dialect
n372+.. attribute:: csvreader.dialect
349
350   A read-only description of the dialect in use by the parser.
351
352
n353-.. attribute:: csv reader.line_num
n377+.. attribute:: csvreader.line_num
354
355   The number of lines read from the source iterator. This is not the same as the
356   number of records returned, as records can span multiple lines.
n381+ 
382+   .. versionadded:: 2.5
383+ 
384+ 
385+DictReader objects have the following public attribute:
386+ 
387+ 
388+.. attribute:: csvreader.fieldnames
389+ 
390+   If not passed as a parameter when creating the object, this attribute is
391+   initialized upon first access or when the first record is read from the
392+   file.
393+ 
394+   .. versionchanged:: 2.6
357
358
359Writer Objects
360--------------
361
362:class:`Writer` objects (:class:`DictWriter` instances and objects returned by
363the :func:`writer` function) have the following public methods.  A *row* must be
364a sequence of strings or numbers for :class:`Writer` objects and a dictionary
365mapping fieldnames to strings or numbers (by passing them through :func:`str`
366first) for :class:`DictWriter` objects.  Note that complex numbers are written
367out surrounded by parens. This may cause some problems for other programs which
368read CSV files (assuming they support complex numbers at all).
369
370
n371-.. method:: csv writer.writerow(row)
n409+.. method:: csvwriter.writerow(row)
372
373   Write the *row* parameter to the writer's file object, formatted according to
374   the current dialect.
375
376
n377-.. method:: csv writer.writerows(rows)
n415+.. method:: csvwriter.writerows(rows)
378
379   Write all the *rows* parameters (a list of *row* objects as described above) to
380   the writer's file object, formatted according to the current dialect.
381
382Writer objects have the following public attribute:
383
384
n385-.. attribute:: csv writer.dialect
n423+.. attribute:: csvwriter.dialect
386
387   A read-only description of the dialect in use by the writer.
388
389
390.. _csv-examples:
391
392Examples
393--------
438   for row in csv.reader(['one,two,three']):
439       print row
440
441The :mod:`csv` module doesn't directly support reading and writing Unicode, but
442it is 8-bit-clean save for some problems with ASCII NUL characters.  So you can
443write functions or classes that handle the encoding and decoding for you as long
444as you avoid encodings like UTF-16 that use NULs.  UTF-8 is recommended.
445
n446-:func:`unicode_csv_reader` below is a generator that wraps :class:`csv.reader`
n484+:func:`unicode_csv_reader` below is a :term:`generator` that wraps :class:`csv.reader`
447to handle Unicode CSV data (a list of Unicode strings).  :func:`utf_8_encoder`
t448-is a generator that encodes the Unicode strings as UTF-8, one string (or row) at
t486+is a :term:`generator` that encodes the Unicode strings as UTF-8, one string (or row) at
449a time.  The encoded strings are parsed by the CSV reader, and
450:func:`unicode_csv_reader` decodes the UTF-8-encoded cells back into Unicode::
451
452   import csv
453
454   def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
455       # csv.py doesn't do Unicode; encode temporarily as UTF-8:
456       csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op