Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame^] | 1 | |
| 2 | :mod:`csv` --- CSV File Reading and Writing |
| 3 | =========================================== |
| 4 | |
| 5 | .. module:: csv |
| 6 | :synopsis: Write and read tabular data to and from delimited files. |
| 7 | .. sectionauthor:: Skip Montanaro <skip@pobox.com> |
| 8 | |
| 9 | |
| 10 | .. versionadded:: 2.3 |
| 11 | |
| 12 | .. index:: |
| 13 | single: csv |
| 14 | pair: data; tabular |
| 15 | |
| 16 | The so-called CSV (Comma Separated Values) format is the most common import and |
| 17 | export format for spreadsheets and databases. There is no "CSV standard", so |
| 18 | the format is operationally defined by the many applications which read and |
| 19 | write it. The lack of a standard means that subtle differences often exist in |
| 20 | the data produced and consumed by different applications. These differences can |
| 21 | make it annoying to process CSV files from multiple sources. Still, while the |
| 22 | delimiters and quoting characters vary, the overall format is similar enough |
| 23 | that it is possible to write a single module which can efficiently manipulate |
| 24 | such data, hiding the details of reading and writing the data from the |
| 25 | programmer. |
| 26 | |
| 27 | The :mod:`csv` module implements classes to read and write tabular data in CSV |
| 28 | format. It allows programmers to say, "write this data in the format preferred |
| 29 | by Excel," or "read data from this file which was generated by Excel," without |
| 30 | knowing the precise details of the CSV format used by Excel. Programmers can |
| 31 | also describe the CSV formats understood by other applications or define their |
| 32 | own special-purpose CSV formats. |
| 33 | |
| 34 | The :mod:`csv` module's :class:`reader` and :class:`writer` objects read and |
| 35 | write sequences. Programmers can also read and write data in dictionary form |
| 36 | using the :class:`DictReader` and :class:`DictWriter` classes. |
| 37 | |
| 38 | .. note:: |
| 39 | |
| 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 | |
| 48 | .. % \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 | |
| 56 | Module Contents |
| 57 | --------------- |
| 58 | |
| 59 | The :mod:`csv` module defines the following functions: |
| 60 | |
| 61 | |
| 62 | .. function:: reader(csvfile[, dialect='excel'][, fmtparam]) |
| 63 | |
| 64 | Return a reader object which will iterate over lines in the given *csvfile*. |
| 65 | *csvfile* can be any object which supports the 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 |
| 74 | dialect. For full details about the dialect and formatting parameters, see |
| 75 | section :ref:`csv-fmt-params`. |
| 76 | |
| 77 | All data read are returned as strings. No automatic data type conversion is |
| 78 | performed. |
| 79 | |
| 80 | .. versionchanged:: 2.5 |
| 81 | The parser is now stricter with respect to multi-line quoted fields. Previously, |
| 82 | if a line ended within a quoted field without a terminating newline character, a |
| 83 | newline would be inserted into the returned field. This behavior caused problems |
| 84 | when reading files which contained carriage return characters within fields. |
| 85 | The behavior was changed to return the field without inserting newlines. As a |
| 86 | consequence, if newlines embedded within fields are important, the input should |
| 87 | be split into lines in a manner which preserves the newline characters. |
| 88 | |
| 89 | |
| 90 | .. function:: writer(csvfile[, dialect='excel'][, fmtparam]) |
| 91 | |
| 92 | Return a writer object responsible for converting the user's data into delimited |
| 93 | strings on the given file-like object. *csvfile* can be any object with a |
| 94 | :func:`write` method. If *csvfile* is a file object, it must be opened with the |
| 95 | 'b' flag on platforms where that makes a difference. An optional *dialect* |
| 96 | parameter can be given which is used to define a set of parameters specific to a |
| 97 | particular CSV dialect. It may be an instance of a subclass of the |
| 98 | :class:`Dialect` class or one of the strings returned by the |
| 99 | :func:`list_dialects` function. The other optional *fmtparam* keyword arguments |
| 100 | can be given to override individual formatting parameters in the current |
| 101 | dialect. For full details about the dialect and formatting parameters, see |
| 102 | section :ref:`csv-fmt-params`. To make it |
| 103 | as easy as possible to interface with modules which implement the DB API, the |
| 104 | value :const:`None` is written as the empty string. While this isn't a |
| 105 | reversible transformation, it makes it easier to dump SQL NULL data values to |
| 106 | CSV files without preprocessing the data returned from a ``cursor.fetch*`` call. |
| 107 | All other non-string data are stringified with :func:`str` before being written. |
| 108 | |
| 109 | |
| 110 | .. function:: register_dialect(name[, dialect][, fmtparam]) |
| 111 | |
| 112 | Associate *dialect* with *name*. *name* must be a string or Unicode object. The |
| 113 | dialect can be specified either by passing a sub-class of :class:`Dialect`, or |
| 114 | by *fmtparam* keyword arguments, or both, with keyword arguments overriding |
| 115 | parameters of the dialect. For full details about the dialect and formatting |
| 116 | parameters, see section :ref:`csv-fmt-params`. |
| 117 | |
| 118 | |
| 119 | .. function:: unregister_dialect(name) |
| 120 | |
| 121 | Delete the dialect associated with *name* from the dialect registry. An |
| 122 | :exc:`Error` is raised if *name* is not a registered dialect name. |
| 123 | |
| 124 | |
| 125 | .. function:: get_dialect(name) |
| 126 | |
| 127 | Return the dialect associated with *name*. An :exc:`Error` is raised if *name* |
| 128 | is not a registered dialect name. |
| 129 | |
| 130 | |
| 131 | .. function:: list_dialects() |
| 132 | |
| 133 | Return the names of all registered dialects. |
| 134 | |
| 135 | |
| 136 | .. function:: field_size_limit([new_limit]) |
| 137 | |
| 138 | Returns the current maximum field size allowed by the parser. If *new_limit* is |
| 139 | given, this becomes the new limit. |
| 140 | |
| 141 | .. versionadded:: 2.5 |
| 142 | |
| 143 | The :mod:`csv` module defines the following classes: |
| 144 | |
| 145 | |
| 146 | .. class:: DictReader(csvfile[, fieldnames=:const:None,[, restkey=:const:None[, restval=None[, dialect='excel'[, *args, **kwds]]]]]) |
| 147 | |
| 148 | Create an object which operates like a regular reader but maps the information |
| 149 | read into a dict whose keys are given by the optional *fieldnames* parameter. |
| 150 | If the *fieldnames* parameter is omitted, the values in the first row of the |
| 151 | *csvfile* will be used as the fieldnames. If the row read has fewer fields than |
| 152 | the fieldnames sequence, the value of *restval* will be used as the default |
| 153 | value. If the row read has more fields than the fieldnames sequence, the |
| 154 | remaining data is added as a sequence keyed by the value of *restkey*. If the |
| 155 | row read has fewer fields than the fieldnames sequence, the remaining keys take |
| 156 | the value of the optional *restval* parameter. Any other optional or keyword |
| 157 | arguments are passed to the underlying :class:`reader` instance. |
| 158 | |
| 159 | |
| 160 | .. class:: DictWriter(csvfile, fieldnames[, restval=''[, extrasaction='raise'[, dialect='excel'[, *args, **kwds]]]]) |
| 161 | |
| 162 | Create an object which operates like a regular writer but maps dictionaries onto |
| 163 | output rows. The *fieldnames* parameter identifies the order in which values in |
| 164 | the dictionary passed to the :meth:`writerow` method are written to the |
| 165 | *csvfile*. The optional *restval* parameter specifies the value to be written |
| 166 | if the dictionary is missing a key in *fieldnames*. If the dictionary passed to |
| 167 | the :meth:`writerow` method contains a key not found in *fieldnames*, the |
| 168 | optional *extrasaction* parameter indicates what action to take. If it is set |
| 169 | to ``'raise'`` a :exc:`ValueError` is raised. If it is set to ``'ignore'``, |
| 170 | extra values in the dictionary are ignored. Any other optional or keyword |
| 171 | arguments are passed to the underlying :class:`writer` instance. |
| 172 | |
| 173 | Note that unlike the :class:`DictReader` class, the *fieldnames* parameter of |
| 174 | the :class:`DictWriter` is not optional. Since Python's :class:`dict` objects |
| 175 | are not ordered, there is not enough information available to deduce the order |
| 176 | in which the row should be written to the *csvfile*. |
| 177 | |
| 178 | |
| 179 | .. class:: Dialect |
| 180 | |
| 181 | The :class:`Dialect` class is a container class relied on primarily for its |
| 182 | attributes, which are used to define the parameters for a specific |
| 183 | :class:`reader` or :class:`writer` instance. |
| 184 | |
| 185 | |
| 186 | .. class:: excel() |
| 187 | |
| 188 | The :class:`excel` class defines the usual properties of an Excel-generated CSV |
| 189 | file. It is registered with the dialect name ``'excel'``. |
| 190 | |
| 191 | |
| 192 | .. class:: excel_tab() |
| 193 | |
| 194 | The :class:`excel_tab` class defines the usual properties of an Excel-generated |
| 195 | TAB-delimited file. It is registered with the dialect name ``'excel-tab'``. |
| 196 | |
| 197 | |
| 198 | .. class:: Sniffer() |
| 199 | |
| 200 | The :class:`Sniffer` class is used to deduce the format of a CSV file. |
| 201 | |
| 202 | The :class:`Sniffer` class provides two methods: |
| 203 | |
| 204 | |
| 205 | .. method:: Sniffer.sniff(sample[, delimiters=None]) |
| 206 | |
| 207 | Analyze the given *sample* and return a :class:`Dialect` subclass reflecting the |
| 208 | parameters found. If the optional *delimiters* parameter is given, it is |
| 209 | interpreted as a string containing possible valid delimiter characters. |
| 210 | |
| 211 | |
| 212 | .. method:: Sniffer.has_header(sample) |
| 213 | |
| 214 | Analyze the sample text (presumed to be in CSV format) and return :const:`True` |
| 215 | if the first row appears to be a series of column headers. |
| 216 | |
| 217 | The :mod:`csv` module defines the following constants: |
| 218 | |
| 219 | |
| 220 | .. data:: QUOTE_ALL |
| 221 | |
| 222 | Instructs :class:`writer` objects to quote all fields. |
| 223 | |
| 224 | |
| 225 | .. data:: QUOTE_MINIMAL |
| 226 | |
| 227 | Instructs :class:`writer` objects to only quote those fields which contain |
| 228 | special characters such as *delimiter*, *quotechar* or any of the characters in |
| 229 | *lineterminator*. |
| 230 | |
| 231 | |
| 232 | .. data:: QUOTE_NONNUMERIC |
| 233 | |
| 234 | Instructs :class:`writer` objects to quote all non-numeric fields. |
| 235 | |
| 236 | Instructs the reader to convert all non-quoted fields to type *float*. |
| 237 | |
| 238 | |
| 239 | .. data:: QUOTE_NONE |
| 240 | |
| 241 | Instructs :class:`writer` objects to never quote fields. When the current |
| 242 | *delimiter* occurs in output data it is preceded by the current *escapechar* |
| 243 | character. If *escapechar* is not set, the writer will raise :exc:`Error` if |
| 244 | any characters that require escaping are encountered. |
| 245 | |
| 246 | Instructs :class:`reader` to perform no special processing of quote characters. |
| 247 | |
| 248 | The :mod:`csv` module defines the following exception: |
| 249 | |
| 250 | |
| 251 | .. exception:: Error |
| 252 | |
| 253 | Raised by any of the functions when an error is detected. |
| 254 | |
| 255 | |
| 256 | .. _csv-fmt-params: |
| 257 | |
| 258 | Dialects and Formatting Parameters |
| 259 | ---------------------------------- |
| 260 | |
| 261 | To make it easier to specify the format of input and output records, specific |
| 262 | formatting parameters are grouped together into dialects. A dialect is a |
| 263 | subclass of the :class:`Dialect` class having a set of specific methods and a |
| 264 | single :meth:`validate` method. When creating :class:`reader` or |
| 265 | :class:`writer` objects, the programmer can specify a string or a subclass of |
| 266 | the :class:`Dialect` class as the dialect parameter. In addition to, or instead |
| 267 | of, the *dialect* parameter, the programmer can also specify individual |
| 268 | formatting parameters, which have the same names as the attributes defined below |
| 269 | for the :class:`Dialect` class. |
| 270 | |
| 271 | Dialects support the following attributes: |
| 272 | |
| 273 | |
| 274 | .. attribute:: Dialect.delimiter |
| 275 | |
| 276 | A one-character string used to separate fields. It defaults to ``','``. |
| 277 | |
| 278 | |
| 279 | .. attribute:: Dialect.doublequote |
| 280 | |
| 281 | Controls how instances of *quotechar* appearing inside a field should be |
| 282 | themselves be quoted. When :const:`True`, the character is doubled. When |
| 283 | :const:`False`, the *escapechar* is used as a prefix to the *quotechar*. It |
| 284 | defaults to :const:`True`. |
| 285 | |
| 286 | On output, if *doublequote* is :const:`False` and no *escapechar* is set, |
| 287 | :exc:`Error` is raised if a *quotechar* is found in a field. |
| 288 | |
| 289 | |
| 290 | .. attribute:: Dialect.escapechar |
| 291 | |
| 292 | A one-character string used by the writer to escape the *delimiter* if *quoting* |
| 293 | is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* is |
| 294 | :const:`False`. On reading, the *escapechar* removes any special meaning from |
| 295 | the following character. It defaults to :const:`None`, which disables escaping. |
| 296 | |
| 297 | |
| 298 | .. attribute:: Dialect.lineterminator |
| 299 | |
| 300 | The string used to terminate lines produced by the :class:`writer`. It defaults |
| 301 | to ``'\r\n'``. |
| 302 | |
| 303 | .. note:: |
| 304 | |
| 305 | The :class:`reader` is hard-coded to recognise either ``'\r'`` or ``'\n'`` as |
| 306 | end-of-line, and ignores *lineterminator*. This behavior may change in the |
| 307 | future. |
| 308 | |
| 309 | |
| 310 | .. attribute:: Dialect.quotechar |
| 311 | |
| 312 | A one-character string used to quote fields containing special characters, such |
| 313 | as the *delimiter* or *quotechar*, or which contain new-line characters. It |
| 314 | defaults to ``'"'``. |
| 315 | |
| 316 | |
| 317 | .. attribute:: Dialect.quoting |
| 318 | |
| 319 | Controls when quotes should be generated by the writer and recognised by the |
| 320 | reader. It can take on any of the :const:`QUOTE_\*` constants (see section |
| 321 | :ref:`csv-contents`) and defaults to :const:`QUOTE_MINIMAL`. |
| 322 | |
| 323 | |
| 324 | .. attribute:: Dialect.skipinitialspace |
| 325 | |
| 326 | When :const:`True`, whitespace immediately following the *delimiter* is ignored. |
| 327 | The default is :const:`False`. |
| 328 | |
| 329 | |
| 330 | Reader Objects |
| 331 | -------------- |
| 332 | |
| 333 | Reader objects (:class:`DictReader` instances and objects returned by the |
| 334 | :func:`reader` function) have the following public methods: |
| 335 | |
| 336 | |
| 337 | .. method:: csvreader.next() |
| 338 | |
| 339 | Return the next row of the reader's iterable object as a list, parsed according |
| 340 | to the current dialect. |
| 341 | |
| 342 | Reader objects have the following public attributes: |
| 343 | |
| 344 | |
| 345 | .. attribute:: csvreader.dialect |
| 346 | |
| 347 | A read-only description of the dialect in use by the parser. |
| 348 | |
| 349 | |
| 350 | .. attribute:: csvreader.line_num |
| 351 | |
| 352 | The number of lines read from the source iterator. This is not the same as the |
| 353 | number of records returned, as records can span multiple lines. |
| 354 | |
| 355 | .. versionadded:: 2.5 |
| 356 | |
| 357 | |
| 358 | Writer Objects |
| 359 | -------------- |
| 360 | |
| 361 | :class:`Writer` objects (:class:`DictWriter` instances and objects returned by |
| 362 | the :func:`writer` function) have the following public methods. A *row* must be |
| 363 | a sequence of strings or numbers for :class:`Writer` objects and a dictionary |
| 364 | mapping fieldnames to strings or numbers (by passing them through :func:`str` |
| 365 | first) for :class:`DictWriter` objects. Note that complex numbers are written |
| 366 | out surrounded by parens. This may cause some problems for other programs which |
| 367 | read CSV files (assuming they support complex numbers at all). |
| 368 | |
| 369 | |
| 370 | .. method:: csvwriter.writerow(row) |
| 371 | |
| 372 | Write the *row* parameter to the writer's file object, formatted according to |
| 373 | the current dialect. |
| 374 | |
| 375 | |
| 376 | .. method:: csvwriter.writerows(rows) |
| 377 | |
| 378 | Write all the *rows* parameters (a list of *row* objects as described above) to |
| 379 | the writer's file object, formatted according to the current dialect. |
| 380 | |
| 381 | Writer objects have the following public attribute: |
| 382 | |
| 383 | |
| 384 | .. attribute:: csvwriter.dialect |
| 385 | |
| 386 | A read-only description of the dialect in use by the writer. |
| 387 | |
| 388 | |
| 389 | .. _csv-examples: |
| 390 | |
| 391 | Examples |
| 392 | -------- |
| 393 | |
| 394 | The simplest example of reading a CSV file:: |
| 395 | |
| 396 | import csv |
| 397 | reader = csv.reader(open("some.csv", "rb")) |
| 398 | for row in reader: |
| 399 | print row |
| 400 | |
| 401 | Reading a file with an alternate format:: |
| 402 | |
| 403 | import csv |
| 404 | reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE) |
| 405 | for row in reader: |
| 406 | print row |
| 407 | |
| 408 | The corresponding simplest possible writing example is:: |
| 409 | |
| 410 | import csv |
| 411 | writer = csv.writer(open("some.csv", "wb")) |
| 412 | writer.writerows(someiterable) |
| 413 | |
| 414 | Registering a new dialect:: |
| 415 | |
| 416 | import csv |
| 417 | |
| 418 | csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE) |
| 419 | |
| 420 | reader = csv.reader(open("passwd", "rb"), 'unixpwd') |
| 421 | |
| 422 | A slightly more advanced use of the reader --- catching and reporting errors:: |
| 423 | |
| 424 | import csv, sys |
| 425 | filename = "some.csv" |
| 426 | reader = csv.reader(open(filename, "rb")) |
| 427 | try: |
| 428 | for row in reader: |
| 429 | print row |
| 430 | except csv.Error as e: |
| 431 | sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) |
| 432 | |
| 433 | And while the module doesn't directly support parsing strings, it can easily be |
| 434 | done:: |
| 435 | |
| 436 | import csv |
| 437 | for row in csv.reader(['one,two,three']): |
| 438 | print row |
| 439 | |
| 440 | The :mod:`csv` module doesn't directly support reading and writing Unicode, but |
| 441 | it is 8-bit-clean save for some problems with ASCII NUL characters. So you can |
| 442 | write functions or classes that handle the encoding and decoding for you as long |
| 443 | as you avoid encodings like UTF-16 that use NULs. UTF-8 is recommended. |
| 444 | |
| 445 | :func:`unicode_csv_reader` below is a generator that wraps :class:`csv.reader` |
| 446 | to handle Unicode CSV data (a list of Unicode strings). :func:`utf_8_encoder` |
| 447 | is a generator that encodes the Unicode strings as UTF-8, one string (or row) at |
| 448 | a time. The encoded strings are parsed by the CSV reader, and |
| 449 | :func:`unicode_csv_reader` decodes the UTF-8-encoded cells back into Unicode:: |
| 450 | |
| 451 | import csv |
| 452 | |
| 453 | def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): |
| 454 | # csv.py doesn't do Unicode; encode temporarily as UTF-8: |
| 455 | csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), |
| 456 | dialect=dialect, **kwargs) |
| 457 | for row in csv_reader: |
| 458 | # decode UTF-8 back to Unicode, cell by cell: |
| 459 | yield [unicode(cell, 'utf-8') for cell in row] |
| 460 | |
| 461 | def utf_8_encoder(unicode_csv_data): |
| 462 | for line in unicode_csv_data: |
| 463 | yield line.encode('utf-8') |
| 464 | |
| 465 | For all other encodings the following :class:`UnicodeReader` and |
| 466 | :class:`UnicodeWriter` classes can be used. They take an additional *encoding* |
| 467 | parameter in their constructor and make sure that the data passes the real |
| 468 | reader or writer encoded as UTF-8:: |
| 469 | |
| 470 | import csv, codecs, cStringIO |
| 471 | |
| 472 | class UTF8Recoder: |
| 473 | """ |
| 474 | Iterator that reads an encoded stream and reencodes the input to UTF-8 |
| 475 | """ |
| 476 | def __init__(self, f, encoding): |
| 477 | self.reader = codecs.getreader(encoding)(f) |
| 478 | |
| 479 | def __iter__(self): |
| 480 | return self |
| 481 | |
| 482 | def __next__(self): |
| 483 | return next(self.reader).encode("utf-8") |
| 484 | |
| 485 | class UnicodeReader: |
| 486 | """ |
| 487 | A CSV reader which will iterate over lines in the CSV file "f", |
| 488 | which is encoded in the given encoding. |
| 489 | """ |
| 490 | |
| 491 | def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): |
| 492 | f = UTF8Recoder(f, encoding) |
| 493 | self.reader = csv.reader(f, dialect=dialect, **kwds) |
| 494 | |
| 495 | def __next__(self): |
| 496 | row = next(self.reader) |
| 497 | return [unicode(s, "utf-8") for s in row] |
| 498 | |
| 499 | def __iter__(self): |
| 500 | return self |
| 501 | |
| 502 | class UnicodeWriter: |
| 503 | """ |
| 504 | A CSV writer which will write rows to CSV file "f", |
| 505 | which is encoded in the given encoding. |
| 506 | """ |
| 507 | |
| 508 | def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): |
| 509 | # Redirect output to a queue |
| 510 | self.queue = cStringIO.StringIO() |
| 511 | self.writer = csv.writer(self.queue, dialect=dialect, **kwds) |
| 512 | self.stream = f |
| 513 | self.encoder = codecs.getincrementalencoder(encoding)() |
| 514 | |
| 515 | def writerow(self, row): |
| 516 | self.writer.writerow([s.encode("utf-8") for s in row]) |
| 517 | # Fetch UTF-8 output from the queue ... |
| 518 | data = self.queue.getvalue() |
| 519 | data = data.decode("utf-8") |
| 520 | # ... and reencode it into the target encoding |
| 521 | data = self.encoder.encode(data) |
| 522 | # write to the target stream |
| 523 | self.stream.write(data) |
| 524 | # empty queue |
| 525 | self.queue.truncate(0) |
| 526 | |
| 527 | def writerows(self, rows): |
| 528 | for row in rows: |
| 529 | self.writerow(row) |
| 530 | |