Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`csv` --- CSV File Reading and Writing |
| 2 | =========================================== |
| 3 | |
| 4 | .. module:: csv |
| 5 | :synopsis: Write and read tabular data to and from delimited files. |
| 6 | .. sectionauthor:: Skip Montanaro <skip@pobox.com> |
| 7 | |
| 8 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | .. index:: |
| 10 | single: csv |
| 11 | pair: data; tabular |
| 12 | |
| 13 | The so-called CSV (Comma Separated Values) format is the most common import and |
Skip Montanaro | b40dea7 | 2011-03-19 09:09:30 -0500 | [diff] [blame] | 14 | export format for spreadsheets and databases. CSV format was used for many |
| 15 | years prior to attempts to describe the format in a standardized way in |
| 16 | :rfc:`4180`. The lack of a well-defined standard means that subtle differences |
| 17 | often exist in the data produced and consumed by different applications. These |
| 18 | differences can make it annoying to process CSV files from multiple sources. |
| 19 | Still, while the delimiters and quoting characters vary, the overall format is |
| 20 | similar enough that it is possible to write a single module which can |
| 21 | efficiently manipulate such data, hiding the details of reading and writing the |
| 22 | data from the programmer. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 23 | |
| 24 | The :mod:`csv` module implements classes to read and write tabular data in CSV |
| 25 | format. It allows programmers to say, "write this data in the format preferred |
| 26 | by Excel," or "read data from this file which was generated by Excel," without |
| 27 | knowing the precise details of the CSV format used by Excel. Programmers can |
| 28 | also describe the CSV formats understood by other applications or define their |
| 29 | own special-purpose CSV formats. |
| 30 | |
| 31 | The :mod:`csv` module's :class:`reader` and :class:`writer` objects read and |
| 32 | write sequences. Programmers can also read and write data in dictionary form |
| 33 | using the :class:`DictReader` and :class:`DictWriter` classes. |
| 34 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 35 | .. seealso:: |
| 36 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 37 | :pep:`305` - CSV File API |
| 38 | The Python Enhancement Proposal which proposed this addition to Python. |
| 39 | |
| 40 | |
| 41 | .. _csv-contents: |
| 42 | |
| 43 | Module Contents |
| 44 | --------------- |
| 45 | |
| 46 | The :mod:`csv` module defines the following functions: |
| 47 | |
| 48 | |
R David Murray | 1b00f25 | 2012-08-15 10:43:58 -0400 | [diff] [blame] | 49 | .. index:: |
| 50 | single: universal newlines; csv.reader function |
| 51 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 52 | .. function:: reader(csvfile, dialect='excel', **fmtparams) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 53 | |
| 54 | Return a reader object which will iterate over lines in the given *csvfile*. |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 55 | *csvfile* can be any object which supports the :term:`iterator` protocol and returns a |
Georg Brandl | b30f330 | 2011-01-06 09:23:56 +0000 | [diff] [blame] | 56 | string each time its :meth:`!__next__` method is called --- :term:`file objects |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 57 | <file object>` and list objects are both suitable. If *csvfile* is a file object, |
R David Murray | 9188702 | 2011-03-19 22:30:14 -0400 | [diff] [blame] | 58 | it should be opened with ``newline=''``. [1]_ An optional |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 59 | *dialect* parameter can be given which is used to define a set of parameters |
| 60 | specific to a particular CSV dialect. It may be an instance of a subclass of |
| 61 | the :class:`Dialect` class or one of the strings returned by the |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 62 | :func:`list_dialects` function. The other optional *fmtparams* keyword arguments |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 63 | can be given to override individual formatting parameters in the current |
| 64 | dialect. For full details about the dialect and formatting parameters, see |
| 65 | section :ref:`csv-fmt-params`. |
| 66 | |
Skip Montanaro | 0468df3 | 2009-03-25 00:52:18 +0000 | [diff] [blame] | 67 | Each row read from the csv file is returned as a list of strings. No |
R. David Murray | 8b7d4aa | 2009-04-04 01:38:38 +0000 | [diff] [blame] | 68 | automatic data type conversion is performed unless the ``QUOTE_NONNUMERIC`` format |
| 69 | option is specified (in which case unquoted fields are transformed into floats). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 70 | |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 71 | A short usage example:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 72 | |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 73 | >>> import csv |
Ezio Melotti | e34f8a9 | 2012-09-15 05:51:45 +0300 | [diff] [blame] | 74 | >>> with open('eggs.csv', newline='') as csvfile: |
| 75 | ... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') |
| 76 | ... for row in spamreader: |
| 77 | ... print(', '.join(row)) |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 78 | Spam, Spam, Spam, Spam, Spam, Baked Beans |
| 79 | Spam, Lovely Spam, Wonderful Spam |
| 80 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 81 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 82 | .. function:: writer(csvfile, dialect='excel', **fmtparams) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 83 | |
| 84 | Return a writer object responsible for converting the user's data into delimited |
| 85 | strings on the given file-like object. *csvfile* can be any object with a |
R David Murray | 9c0d5ea | 2011-03-20 11:18:21 -0400 | [diff] [blame] | 86 | :func:`write` method. If *csvfile* is a file object, it should be opened with |
| 87 | ``newline=''`` [1]_. An optional *dialect* |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | parameter can be given which is used to define a set of parameters specific to a |
| 89 | particular CSV dialect. It may be an instance of a subclass of the |
| 90 | :class:`Dialect` class or one of the strings returned by the |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 91 | :func:`list_dialects` function. The other optional *fmtparams* keyword arguments |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 92 | can be given to override individual formatting parameters in the current |
| 93 | dialect. For full details about the dialect and formatting parameters, see |
| 94 | section :ref:`csv-fmt-params`. To make it |
| 95 | as easy as possible to interface with modules which implement the DB API, the |
| 96 | value :const:`None` is written as the empty string. While this isn't a |
| 97 | reversible transformation, it makes it easier to dump SQL NULL data values to |
| 98 | CSV files without preprocessing the data returned from a ``cursor.fetch*`` call. |
| 99 | All other non-string data are stringified with :func:`str` before being written. |
| 100 | |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 101 | A short usage example:: |
| 102 | |
Ezio Melotti | e34f8a9 | 2012-09-15 05:51:45 +0300 | [diff] [blame] | 103 | import csv |
| 104 | with open('eggs.csv', 'w', newline='') as csvfile: |
| 105 | spamwriter = csv.writer(csvfile, delimiter=' ', |
| 106 | quotechar='|', quoting=csv.QUOTE_MINIMAL) |
| 107 | spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) |
| 108 | spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 109 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 110 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 111 | .. function:: register_dialect(name[, dialect], **fmtparams) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 112 | |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 113 | Associate *dialect* with *name*. *name* must be a string. The |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 114 | dialect can be specified either by passing a sub-class of :class:`Dialect`, or |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 115 | by *fmtparams* keyword arguments, or both, with keyword arguments overriding |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 116 | parameters of the dialect. For full details about the dialect and formatting |
| 117 | parameters, see section :ref:`csv-fmt-params`. |
| 118 | |
| 119 | |
| 120 | .. function:: unregister_dialect(name) |
| 121 | |
| 122 | Delete the dialect associated with *name* from the dialect registry. An |
| 123 | :exc:`Error` is raised if *name* is not a registered dialect name. |
| 124 | |
| 125 | |
| 126 | .. function:: get_dialect(name) |
| 127 | |
Georg Brandl | 6554cb9 | 2007-12-02 23:15:43 +0000 | [diff] [blame] | 128 | Return the dialect associated with *name*. An :exc:`Error` is raised if |
| 129 | *name* is not a registered dialect name. This function returns an immutable |
| 130 | :class:`Dialect`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 131 | |
| 132 | .. function:: list_dialects() |
| 133 | |
| 134 | Return the names of all registered dialects. |
| 135 | |
| 136 | |
| 137 | .. function:: field_size_limit([new_limit]) |
| 138 | |
| 139 | Returns the current maximum field size allowed by the parser. If *new_limit* is |
| 140 | given, this becomes the new limit. |
| 141 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 142 | |
| 143 | The :mod:`csv` module defines the following classes: |
| 144 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 145 | .. class:: DictReader(csvfile, fieldnames=None, restkey=None, restval=None, \ |
| 146 | dialect='excel', *args, **kwds) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 147 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 148 | Create an object which operates like a regular reader but maps the |
| 149 | information read into a dict whose keys are given by the optional |
| 150 | *fieldnames* parameter. The *fieldnames* parameter is a :mod:`sequence |
| 151 | <collections.abc>` whose elements are associated with the fields of the |
| 152 | input data in order. These elements become the keys of the resulting |
| 153 | dictionary. If the *fieldnames* parameter is omitted, the values in the |
| 154 | first row of the *csvfile* will be used as the fieldnames. If the row read |
| 155 | has more fields than the fieldnames sequence, the remaining data is added as |
| 156 | a sequence keyed by the value of *restkey*. If the row read has fewer |
| 157 | fields than the fieldnames sequence, the remaining keys take the value of |
| 158 | the optional *restval* parameter. Any other optional or keyword arguments |
| 159 | are passed to the underlying :class:`reader` instance. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 160 | |
| 161 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 162 | .. class:: DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', \ |
| 163 | dialect='excel', *args, **kwds) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 164 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 165 | Create an object which operates like a regular writer but maps dictionaries |
| 166 | onto output rows. The *fieldnames* parameter is a :mod:`sequence |
| 167 | <collections.abc>` of keys that identify the order in which values in the |
| 168 | dictionary passed to the :meth:`writerow` method are written to the |
| 169 | *csvfile*. The optional *restval* parameter specifies the value to be |
| 170 | written if the dictionary is missing a key in *fieldnames*. If the |
| 171 | dictionary passed to the :meth:`writerow` method contains a key not found in |
| 172 | *fieldnames*, the optional *extrasaction* parameter indicates what action to |
| 173 | take. If it is set to ``'raise'`` a :exc:`ValueError` is raised. If it is |
| 174 | set to ``'ignore'``, extra values in the dictionary are ignored. Any other |
| 175 | optional or keyword arguments are passed to the underlying :class:`writer` |
| 176 | instance. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 177 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 178 | Note that unlike the :class:`DictReader` class, the *fieldnames* parameter |
| 179 | of the :class:`DictWriter` is not optional. Since Python's :class:`dict` |
| 180 | objects are not ordered, there is not enough information available to deduce |
| 181 | the order in which the row should be written to the *csvfile*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 182 | |
| 183 | |
| 184 | .. class:: Dialect |
| 185 | |
| 186 | The :class:`Dialect` class is a container class relied on primarily for its |
| 187 | attributes, which are used to define the parameters for a specific |
| 188 | :class:`reader` or :class:`writer` instance. |
| 189 | |
| 190 | |
| 191 | .. class:: excel() |
| 192 | |
| 193 | The :class:`excel` class defines the usual properties of an Excel-generated CSV |
| 194 | file. It is registered with the dialect name ``'excel'``. |
| 195 | |
| 196 | |
| 197 | .. class:: excel_tab() |
| 198 | |
| 199 | The :class:`excel_tab` class defines the usual properties of an Excel-generated |
| 200 | TAB-delimited file. It is registered with the dialect name ``'excel-tab'``. |
| 201 | |
| 202 | |
Georg Brandl | 7424dd3 | 2010-10-27 07:27:06 +0000 | [diff] [blame] | 203 | .. class:: unix_dialect() |
| 204 | |
| 205 | The :class:`unix_dialect` class defines the usual properties of a CSV file |
| 206 | generated on UNIX systems, i.e. using ``'\n'`` as line terminator and quoting |
| 207 | all fields. It is registered with the dialect name ``'unix'``. |
| 208 | |
| 209 | .. versionadded:: 3.2 |
| 210 | |
| 211 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 212 | .. class:: Sniffer() |
| 213 | |
| 214 | The :class:`Sniffer` class is used to deduce the format of a CSV file. |
| 215 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 216 | The :class:`Sniffer` class provides two methods: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 217 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 218 | .. method:: sniff(sample, delimiters=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 219 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 220 | Analyze the given *sample* and return a :class:`Dialect` subclass |
| 221 | reflecting the parameters found. If the optional *delimiters* parameter |
| 222 | is given, it is interpreted as a string containing possible valid |
| 223 | delimiter characters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 224 | |
| 225 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 226 | .. method:: has_header(sample) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 227 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 228 | Analyze the sample text (presumed to be in CSV format) and return |
| 229 | :const:`True` if the first row appears to be a series of column headers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 230 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 231 | An example for :class:`Sniffer` use:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 232 | |
Ezio Melotti | e34f8a9 | 2012-09-15 05:51:45 +0300 | [diff] [blame] | 233 | with open('example.csv') as csvfile: |
| 234 | dialect = csv.Sniffer().sniff(csvfile.read(1024)) |
| 235 | csvfile.seek(0) |
| 236 | reader = csv.reader(csvfile, dialect) |
| 237 | # ... process CSV file contents here ... |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 238 | |
| 239 | |
| 240 | The :mod:`csv` module defines the following constants: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 241 | |
| 242 | .. data:: QUOTE_ALL |
| 243 | |
| 244 | Instructs :class:`writer` objects to quote all fields. |
| 245 | |
| 246 | |
| 247 | .. data:: QUOTE_MINIMAL |
| 248 | |
| 249 | Instructs :class:`writer` objects to only quote those fields which contain |
| 250 | special characters such as *delimiter*, *quotechar* or any of the characters in |
| 251 | *lineterminator*. |
| 252 | |
| 253 | |
| 254 | .. data:: QUOTE_NONNUMERIC |
| 255 | |
| 256 | Instructs :class:`writer` objects to quote all non-numeric fields. |
| 257 | |
| 258 | Instructs the reader to convert all non-quoted fields to type *float*. |
| 259 | |
| 260 | |
| 261 | .. data:: QUOTE_NONE |
| 262 | |
| 263 | Instructs :class:`writer` objects to never quote fields. When the current |
| 264 | *delimiter* occurs in output data it is preceded by the current *escapechar* |
| 265 | character. If *escapechar* is not set, the writer will raise :exc:`Error` if |
| 266 | any characters that require escaping are encountered. |
| 267 | |
| 268 | Instructs :class:`reader` to perform no special processing of quote characters. |
| 269 | |
| 270 | The :mod:`csv` module defines the following exception: |
| 271 | |
| 272 | |
| 273 | .. exception:: Error |
| 274 | |
| 275 | Raised by any of the functions when an error is detected. |
| 276 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 277 | .. _csv-fmt-params: |
| 278 | |
| 279 | Dialects and Formatting Parameters |
| 280 | ---------------------------------- |
| 281 | |
| 282 | To make it easier to specify the format of input and output records, specific |
| 283 | formatting parameters are grouped together into dialects. A dialect is a |
| 284 | subclass of the :class:`Dialect` class having a set of specific methods and a |
| 285 | single :meth:`validate` method. When creating :class:`reader` or |
| 286 | :class:`writer` objects, the programmer can specify a string or a subclass of |
| 287 | the :class:`Dialect` class as the dialect parameter. In addition to, or instead |
| 288 | of, the *dialect* parameter, the programmer can also specify individual |
| 289 | formatting parameters, which have the same names as the attributes defined below |
| 290 | for the :class:`Dialect` class. |
| 291 | |
| 292 | Dialects support the following attributes: |
| 293 | |
| 294 | |
| 295 | .. attribute:: Dialect.delimiter |
| 296 | |
| 297 | A one-character string used to separate fields. It defaults to ``','``. |
| 298 | |
| 299 | |
| 300 | .. attribute:: Dialect.doublequote |
| 301 | |
| 302 | Controls how instances of *quotechar* appearing inside a field should be |
| 303 | themselves be quoted. When :const:`True`, the character is doubled. When |
| 304 | :const:`False`, the *escapechar* is used as a prefix to the *quotechar*. It |
| 305 | defaults to :const:`True`. |
| 306 | |
| 307 | On output, if *doublequote* is :const:`False` and no *escapechar* is set, |
| 308 | :exc:`Error` is raised if a *quotechar* is found in a field. |
| 309 | |
| 310 | |
| 311 | .. attribute:: Dialect.escapechar |
| 312 | |
| 313 | A one-character string used by the writer to escape the *delimiter* if *quoting* |
| 314 | is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* is |
| 315 | :const:`False`. On reading, the *escapechar* removes any special meaning from |
| 316 | the following character. It defaults to :const:`None`, which disables escaping. |
| 317 | |
| 318 | |
| 319 | .. attribute:: Dialect.lineterminator |
| 320 | |
| 321 | The string used to terminate lines produced by the :class:`writer`. It defaults |
| 322 | to ``'\r\n'``. |
| 323 | |
| 324 | .. note:: |
| 325 | |
| 326 | The :class:`reader` is hard-coded to recognise either ``'\r'`` or ``'\n'`` as |
| 327 | end-of-line, and ignores *lineterminator*. This behavior may change in the |
| 328 | future. |
| 329 | |
| 330 | |
| 331 | .. attribute:: Dialect.quotechar |
| 332 | |
| 333 | A one-character string used to quote fields containing special characters, such |
| 334 | as the *delimiter* or *quotechar*, or which contain new-line characters. It |
| 335 | defaults to ``'"'``. |
| 336 | |
| 337 | |
| 338 | .. attribute:: Dialect.quoting |
| 339 | |
| 340 | Controls when quotes should be generated by the writer and recognised by the |
| 341 | reader. It can take on any of the :const:`QUOTE_\*` constants (see section |
| 342 | :ref:`csv-contents`) and defaults to :const:`QUOTE_MINIMAL`. |
| 343 | |
| 344 | |
| 345 | .. attribute:: Dialect.skipinitialspace |
| 346 | |
| 347 | When :const:`True`, whitespace immediately following the *delimiter* is ignored. |
| 348 | The default is :const:`False`. |
| 349 | |
| 350 | |
Ezio Melotti | a69be28 | 2012-11-18 12:55:35 +0200 | [diff] [blame] | 351 | .. attribute:: Dialect.strict |
| 352 | |
| 353 | When ``True``, raise exception :exc:`Error` on bad CSV input. |
| 354 | The default is ``False``. |
| 355 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 356 | Reader Objects |
| 357 | -------------- |
| 358 | |
| 359 | Reader objects (:class:`DictReader` instances and objects returned by the |
| 360 | :func:`reader` function) have the following public methods: |
| 361 | |
Georg Brandl | c748506 | 2009-04-01 15:53:15 +0000 | [diff] [blame] | 362 | .. method:: csvreader.__next__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 363 | |
| 364 | Return the next row of the reader's iterable object as a list, parsed according |
Georg Brandl | c748506 | 2009-04-01 15:53:15 +0000 | [diff] [blame] | 365 | to the current dialect. Usually you should call this as ``next(reader)``. |
| 366 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 367 | |
| 368 | Reader objects have the following public attributes: |
| 369 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 370 | .. attribute:: csvreader.dialect |
| 371 | |
| 372 | A read-only description of the dialect in use by the parser. |
| 373 | |
| 374 | |
| 375 | .. attribute:: csvreader.line_num |
| 376 | |
| 377 | The number of lines read from the source iterator. This is not the same as the |
| 378 | number of records returned, as records can span multiple lines. |
| 379 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 380 | |
Skip Montanaro | af8fcfa | 2008-08-09 19:44:22 +0000 | [diff] [blame] | 381 | DictReader objects have the following public attribute: |
| 382 | |
Skip Montanaro | af8fcfa | 2008-08-09 19:44:22 +0000 | [diff] [blame] | 383 | .. attribute:: csvreader.fieldnames |
| 384 | |
| 385 | If not passed as a parameter when creating the object, this attribute is |
| 386 | initialized upon first access or when the first record is read from the |
| 387 | file. |
| 388 | |
Skip Montanaro | af8fcfa | 2008-08-09 19:44:22 +0000 | [diff] [blame] | 389 | |
| 390 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 391 | Writer Objects |
| 392 | -------------- |
| 393 | |
| 394 | :class:`Writer` objects (:class:`DictWriter` instances and objects returned by |
| 395 | the :func:`writer` function) have the following public methods. A *row* must be |
| 396 | a sequence of strings or numbers for :class:`Writer` objects and a dictionary |
| 397 | mapping fieldnames to strings or numbers (by passing them through :func:`str` |
| 398 | first) for :class:`DictWriter` objects. Note that complex numbers are written |
| 399 | out surrounded by parens. This may cause some problems for other programs which |
| 400 | read CSV files (assuming they support complex numbers at all). |
| 401 | |
| 402 | |
| 403 | .. method:: csvwriter.writerow(row) |
| 404 | |
| 405 | Write the *row* parameter to the writer's file object, formatted according to |
| 406 | the current dialect. |
| 407 | |
| 408 | |
| 409 | .. method:: csvwriter.writerows(rows) |
| 410 | |
| 411 | Write all the *rows* parameters (a list of *row* objects as described above) to |
| 412 | the writer's file object, formatted according to the current dialect. |
| 413 | |
| 414 | Writer objects have the following public attribute: |
| 415 | |
| 416 | |
| 417 | .. attribute:: csvwriter.dialect |
| 418 | |
| 419 | A read-only description of the dialect in use by the writer. |
| 420 | |
| 421 | |
R. David Murray | be0698b | 2010-02-23 22:57:58 +0000 | [diff] [blame] | 422 | DictWriter objects have the following public method: |
| 423 | |
| 424 | |
| 425 | .. method:: DictWriter.writeheader() |
| 426 | |
| 427 | Write a row with the field names (as specified in the constructor). |
| 428 | |
R. David Murray | 19e4548 | 2010-02-23 23:00:34 +0000 | [diff] [blame] | 429 | .. versionadded:: 3.2 |
R. David Murray | be0698b | 2010-02-23 22:57:58 +0000 | [diff] [blame] | 430 | |
| 431 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 432 | .. _csv-examples: |
| 433 | |
| 434 | Examples |
| 435 | -------- |
| 436 | |
| 437 | The simplest example of reading a CSV file:: |
| 438 | |
| 439 | import csv |
Eli Bendersky | 6860a92 | 2011-03-11 15:47:36 +0200 | [diff] [blame] | 440 | with open('some.csv', newline='') as f: |
| 441 | reader = csv.reader(f) |
| 442 | for row in reader: |
| 443 | print(row) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 444 | |
| 445 | Reading a file with an alternate format:: |
| 446 | |
| 447 | import csv |
R David Murray | 9188702 | 2011-03-19 22:30:14 -0400 | [diff] [blame] | 448 | with open('passwd', newline='') as f: |
Eli Bendersky | 6860a92 | 2011-03-11 15:47:36 +0200 | [diff] [blame] | 449 | reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE) |
| 450 | for row in reader: |
| 451 | print(row) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 452 | |
| 453 | The corresponding simplest possible writing example is:: |
| 454 | |
| 455 | import csv |
R David Murray | 9188702 | 2011-03-19 22:30:14 -0400 | [diff] [blame] | 456 | with open('some.csv', 'w', newline='') as f: |
Eli Bendersky | 6860a92 | 2011-03-11 15:47:36 +0200 | [diff] [blame] | 457 | writer = csv.writer(f) |
| 458 | writer.writerows(someiterable) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 459 | |
R. David Murray | 8b7d4aa | 2009-04-04 01:38:38 +0000 | [diff] [blame] | 460 | Since :func:`open` is used to open a CSV file for reading, the file |
| 461 | will by default be decoded into unicode using the system default |
| 462 | encoding (see :func:`locale.getpreferredencoding`). To decode a file |
| 463 | using a different encoding, use the ``encoding`` argument of open:: |
| 464 | |
Eli Bendersky | 6860a92 | 2011-03-11 15:47:36 +0200 | [diff] [blame] | 465 | import csv |
| 466 | with open('some.csv', newline='', encoding='utf-8') as f: |
| 467 | reader = csv.reader(f) |
| 468 | for row in reader: |
| 469 | print(row) |
R. David Murray | 8b7d4aa | 2009-04-04 01:38:38 +0000 | [diff] [blame] | 470 | |
| 471 | The same applies to writing in something other than the system default |
| 472 | encoding: specify the encoding argument when opening the output file. |
| 473 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 474 | Registering a new dialect:: |
| 475 | |
| 476 | import csv |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 477 | csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE) |
R David Murray | 9188702 | 2011-03-19 22:30:14 -0400 | [diff] [blame] | 478 | with open('passwd', newline='') as f: |
Eli Bendersky | 6860a92 | 2011-03-11 15:47:36 +0200 | [diff] [blame] | 479 | reader = csv.reader(f, 'unixpwd') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 480 | |
| 481 | A slightly more advanced use of the reader --- catching and reporting errors:: |
| 482 | |
| 483 | import csv, sys |
Eli Bendersky | 6860a92 | 2011-03-11 15:47:36 +0200 | [diff] [blame] | 484 | filename = 'some.csv' |
| 485 | with open(filename, newline='') as f: |
| 486 | reader = csv.reader(f) |
| 487 | try: |
| 488 | for row in reader: |
| 489 | print(row) |
| 490 | except csv.Error as e: |
| 491 | sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 492 | |
| 493 | And while the module doesn't directly support parsing strings, it can easily be |
| 494 | done:: |
| 495 | |
| 496 | import csv |
| 497 | for row in csv.reader(['one,two,three']): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 498 | print(row) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 499 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 500 | |
R. David Murray | 8b7d4aa | 2009-04-04 01:38:38 +0000 | [diff] [blame] | 501 | .. rubric:: Footnotes |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 502 | |
R David Murray | 9188702 | 2011-03-19 22:30:14 -0400 | [diff] [blame] | 503 | .. [1] If ``newline=''`` is not specified, newlines embedded inside quoted fields |
| 504 | will not be interpreted correctly, and on platforms that use ``\r\n`` linendings |
R David Murray | 9c0d5ea | 2011-03-20 11:18:21 -0400 | [diff] [blame] | 505 | on write an extra ``\r`` will be added. It should always be safe to specify |
R David Murray | 1b00f25 | 2012-08-15 10:43:58 -0400 | [diff] [blame] | 506 | ``newline=''``, since the csv module does its own |
| 507 | (:term:`universal <universal newlines>`) newline handling. |