blob: 1be909bbead8b91bd794726e1eadee8389ddce86 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
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
16The so-called CSV (Comma Separated Values) format is the most common import and
17export format for spreadsheets and databases. There is no "CSV standard", so
18the format is operationally defined by the many applications which read and
19write it. The lack of a standard means that subtle differences often exist in
20the data produced and consumed by different applications. These differences can
21make it annoying to process CSV files from multiple sources. Still, while the
22delimiters and quoting characters vary, the overall format is similar enough
23that it is possible to write a single module which can efficiently manipulate
24such data, hiding the details of reading and writing the data from the
25programmer.
26
27The :mod:`csv` module implements classes to read and write tabular data in CSV
28format. It allows programmers to say, "write this data in the format preferred
29by Excel," or "read data from this file which was generated by Excel," without
30knowing the precise details of the CSV format used by Excel. Programmers can
31also describe the CSV formats understood by other applications or define their
32own special-purpose CSV formats.
33
34The :mod:`csv` module's :class:`reader` and :class:`writer` objects read and
35write sequences. Programmers can also read and write data in dictionary form
36using 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
56Module Contents
57---------------
58
59The :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*.
Georg Brandle7a09902007-10-21 12:10:28 +000065 *csvfile* can be any object which supports the :term:`iterator` protocol and returns a
Georg Brandl8ec7f652007-08-15 14:28:01 +000066 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
Skip Montanarod469ff12007-11-04 15:56:52 +0000130 .. versionchanged:: 2.5
131
132 This function now returns an immutable :class:`Dialect`. Previously an
133 instance of the requested dialect was returned. Users could modify the
134 underlying class, changing the behavior of active readers and writers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000135
136.. function:: list_dialects()
137
138 Return the names of all registered dialects.
139
140
141.. function:: field_size_limit([new_limit])
142
143 Returns the current maximum field size allowed by the parser. If *new_limit* is
144 given, this becomes the new limit.
145
146 .. versionadded:: 2.5
147
148The :mod:`csv` module defines the following classes:
149
150
Brett Cannon1f67a672007-10-16 23:24:06 +0000151.. class:: DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
153 Create an object which operates like a regular reader but maps the information
154 read into a dict whose keys are given by the optional *fieldnames* parameter.
155 If the *fieldnames* parameter is omitted, the values in the first row of the
156 *csvfile* will be used as the fieldnames. If the row read has fewer fields than
157 the fieldnames sequence, the value of *restval* will be used as the default
158 value. If the row read has more fields than the fieldnames sequence, the
159 remaining data is added as a sequence keyed by the value of *restkey*. If the
160 row read has fewer fields than the fieldnames sequence, the remaining keys take
161 the value of the optional *restval* parameter. Any other optional or keyword
162 arguments are passed to the underlying :class:`reader` instance.
163
164
165.. class:: DictWriter(csvfile, fieldnames[, restval=''[, extrasaction='raise'[, dialect='excel'[, *args, **kwds]]]])
166
167 Create an object which operates like a regular writer but maps dictionaries onto
168 output rows. The *fieldnames* parameter identifies the order in which values in
169 the dictionary passed to the :meth:`writerow` method are written to the
170 *csvfile*. The optional *restval* parameter specifies the value to be written
171 if the dictionary is missing a key in *fieldnames*. If the dictionary passed to
172 the :meth:`writerow` method contains a key not found in *fieldnames*, the
173 optional *extrasaction* parameter indicates what action to take. If it is set
174 to ``'raise'`` a :exc:`ValueError` is raised. If it is set to ``'ignore'``,
175 extra values in the dictionary are ignored. Any other optional or keyword
176 arguments are passed to the underlying :class:`writer` instance.
177
178 Note that unlike the :class:`DictReader` class, the *fieldnames* parameter of
179 the :class:`DictWriter` is not optional. Since Python's :class:`dict` objects
180 are not ordered, there is not enough information available to deduce the order
181 in which the row should be written to the *csvfile*.
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
203.. class:: Sniffer()
204
205 The :class:`Sniffer` class is used to deduce the format of a CSV file.
206
207The :class:`Sniffer` class provides two methods:
208
209
210.. method:: Sniffer.sniff(sample[, delimiters=None])
211
212 Analyze the given *sample* and return a :class:`Dialect` subclass reflecting the
213 parameters found. If the optional *delimiters* parameter is given, it is
214 interpreted as a string containing possible valid delimiter characters.
215
216
217.. method:: Sniffer.has_header(sample)
218
219 Analyze the sample text (presumed to be in CSV format) and return :const:`True`
220 if the first row appears to be a series of column headers.
221
222The :mod:`csv` module defines the following constants:
223
224
225.. data:: QUOTE_ALL
226
227 Instructs :class:`writer` objects to quote all fields.
228
229
230.. data:: QUOTE_MINIMAL
231
232 Instructs :class:`writer` objects to only quote those fields which contain
233 special characters such as *delimiter*, *quotechar* or any of the characters in
234 *lineterminator*.
235
236
237.. data:: QUOTE_NONNUMERIC
238
239 Instructs :class:`writer` objects to quote all non-numeric fields.
240
241 Instructs the reader to convert all non-quoted fields to type *float*.
242
243
244.. data:: QUOTE_NONE
245
246 Instructs :class:`writer` objects to never quote fields. When the current
247 *delimiter* occurs in output data it is preceded by the current *escapechar*
248 character. If *escapechar* is not set, the writer will raise :exc:`Error` if
249 any characters that require escaping are encountered.
250
251 Instructs :class:`reader` to perform no special processing of quote characters.
252
253The :mod:`csv` module defines the following exception:
254
255
256.. exception:: Error
257
258 Raised by any of the functions when an error is detected.
259
260
261.. _csv-fmt-params:
262
263Dialects and Formatting Parameters
264----------------------------------
265
266To make it easier to specify the format of input and output records, specific
267formatting parameters are grouped together into dialects. A dialect is a
268subclass of the :class:`Dialect` class having a set of specific methods and a
269single :meth:`validate` method. When creating :class:`reader` or
270:class:`writer` objects, the programmer can specify a string or a subclass of
271the :class:`Dialect` class as the dialect parameter. In addition to, or instead
272of, the *dialect* parameter, the programmer can also specify individual
273formatting parameters, which have the same names as the attributes defined below
274for the :class:`Dialect` class.
275
276Dialects support the following attributes:
277
278
279.. attribute:: Dialect.delimiter
280
281 A one-character string used to separate fields. It defaults to ``','``.
282
283
284.. attribute:: Dialect.doublequote
285
286 Controls how instances of *quotechar* appearing inside a field should be
287 themselves be quoted. When :const:`True`, the character is doubled. When
288 :const:`False`, the *escapechar* is used as a prefix to the *quotechar*. It
289 defaults to :const:`True`.
290
291 On output, if *doublequote* is :const:`False` and no *escapechar* is set,
292 :exc:`Error` is raised if a *quotechar* is found in a field.
293
294
295.. attribute:: Dialect.escapechar
296
297 A one-character string used by the writer to escape the *delimiter* if *quoting*
298 is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* is
299 :const:`False`. On reading, the *escapechar* removes any special meaning from
300 the following character. It defaults to :const:`None`, which disables escaping.
301
302
303.. attribute:: Dialect.lineterminator
304
305 The string used to terminate lines produced by the :class:`writer`. It defaults
306 to ``'\r\n'``.
307
308 .. note::
309
310 The :class:`reader` is hard-coded to recognise either ``'\r'`` or ``'\n'`` as
311 end-of-line, and ignores *lineterminator*. This behavior may change in the
312 future.
313
314
315.. attribute:: Dialect.quotechar
316
317 A one-character string used to quote fields containing special characters, such
318 as the *delimiter* or *quotechar*, or which contain new-line characters. It
319 defaults to ``'"'``.
320
321
322.. attribute:: Dialect.quoting
323
324 Controls when quotes should be generated by the writer and recognised by the
325 reader. It can take on any of the :const:`QUOTE_\*` constants (see section
326 :ref:`csv-contents`) and defaults to :const:`QUOTE_MINIMAL`.
327
328
329.. attribute:: Dialect.skipinitialspace
330
331 When :const:`True`, whitespace immediately following the *delimiter* is ignored.
332 The default is :const:`False`.
333
334
335Reader Objects
336--------------
337
338Reader objects (:class:`DictReader` instances and objects returned by the
339:func:`reader` function) have the following public methods:
340
341
342.. method:: csvreader.next()
343
344 Return the next row of the reader's iterable object as a list, parsed according
345 to the current dialect.
346
347Reader objects have the following public attributes:
348
349
350.. attribute:: csvreader.dialect
351
352 A read-only description of the dialect in use by the parser.
353
354
355.. attribute:: csvreader.line_num
356
357 The number of lines read from the source iterator. This is not the same as the
358 number of records returned, as records can span multiple lines.
359
360 .. versionadded:: 2.5
361
362
363Writer Objects
364--------------
365
366:class:`Writer` objects (:class:`DictWriter` instances and objects returned by
367the :func:`writer` function) have the following public methods. A *row* must be
368a sequence of strings or numbers for :class:`Writer` objects and a dictionary
369mapping fieldnames to strings or numbers (by passing them through :func:`str`
370first) for :class:`DictWriter` objects. Note that complex numbers are written
371out surrounded by parens. This may cause some problems for other programs which
372read CSV files (assuming they support complex numbers at all).
373
374
375.. method:: csvwriter.writerow(row)
376
377 Write the *row* parameter to the writer's file object, formatted according to
378 the current dialect.
379
380
381.. method:: csvwriter.writerows(rows)
382
383 Write all the *rows* parameters (a list of *row* objects as described above) to
384 the writer's file object, formatted according to the current dialect.
385
386Writer objects have the following public attribute:
387
388
389.. attribute:: csvwriter.dialect
390
391 A read-only description of the dialect in use by the writer.
392
393
394.. _csv-examples:
395
396Examples
397--------
398
399The simplest example of reading a CSV file::
400
401 import csv
402 reader = csv.reader(open("some.csv", "rb"))
403 for row in reader:
404 print row
405
406Reading a file with an alternate format::
407
408 import csv
409 reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
410 for row in reader:
411 print row
412
413The corresponding simplest possible writing example is::
414
415 import csv
416 writer = csv.writer(open("some.csv", "wb"))
417 writer.writerows(someiterable)
418
419Registering a new dialect::
420
421 import csv
422
423 csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
424
425 reader = csv.reader(open("passwd", "rb"), 'unixpwd')
426
427A slightly more advanced use of the reader --- catching and reporting errors::
428
429 import csv, sys
430 filename = "some.csv"
431 reader = csv.reader(open(filename, "rb"))
432 try:
433 for row in reader:
434 print row
435 except csv.Error, e:
436 sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
437
438And while the module doesn't directly support parsing strings, it can easily be
439done::
440
441 import csv
442 for row in csv.reader(['one,two,three']):
443 print row
444
445The :mod:`csv` module doesn't directly support reading and writing Unicode, but
446it is 8-bit-clean save for some problems with ASCII NUL characters. So you can
447write functions or classes that handle the encoding and decoding for you as long
448as you avoid encodings like UTF-16 that use NULs. UTF-8 is recommended.
449
Georg Brandlcf3fb252007-10-21 10:52:38 +0000450:func:`unicode_csv_reader` below is a :term:`generator` that wraps :class:`csv.reader`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000451to handle Unicode CSV data (a list of Unicode strings). :func:`utf_8_encoder`
Georg Brandlcf3fb252007-10-21 10:52:38 +0000452is a :term:`generator` that encodes the Unicode strings as UTF-8, one string (or row) at
Georg Brandl8ec7f652007-08-15 14:28:01 +0000453a time. The encoded strings are parsed by the CSV reader, and
454:func:`unicode_csv_reader` decodes the UTF-8-encoded cells back into Unicode::
455
456 import csv
457
458 def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
459 # csv.py doesn't do Unicode; encode temporarily as UTF-8:
460 csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
461 dialect=dialect, **kwargs)
462 for row in csv_reader:
463 # decode UTF-8 back to Unicode, cell by cell:
464 yield [unicode(cell, 'utf-8') for cell in row]
465
466 def utf_8_encoder(unicode_csv_data):
467 for line in unicode_csv_data:
468 yield line.encode('utf-8')
469
470For all other encodings the following :class:`UnicodeReader` and
471:class:`UnicodeWriter` classes can be used. They take an additional *encoding*
472parameter in their constructor and make sure that the data passes the real
473reader or writer encoded as UTF-8::
474
475 import csv, codecs, cStringIO
476
477 class UTF8Recoder:
478 """
479 Iterator that reads an encoded stream and reencodes the input to UTF-8
480 """
481 def __init__(self, f, encoding):
482 self.reader = codecs.getreader(encoding)(f)
483
484 def __iter__(self):
485 return self
486
487 def next(self):
488 return self.reader.next().encode("utf-8")
489
490 class UnicodeReader:
491 """
492 A CSV reader which will iterate over lines in the CSV file "f",
493 which is encoded in the given encoding.
494 """
495
496 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
497 f = UTF8Recoder(f, encoding)
498 self.reader = csv.reader(f, dialect=dialect, **kwds)
499
500 def next(self):
501 row = self.reader.next()
502 return [unicode(s, "utf-8") for s in row]
503
504 def __iter__(self):
505 return self
506
507 class UnicodeWriter:
508 """
509 A CSV writer which will write rows to CSV file "f",
510 which is encoded in the given encoding.
511 """
512
513 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
514 # Redirect output to a queue
515 self.queue = cStringIO.StringIO()
516 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
517 self.stream = f
518 self.encoder = codecs.getincrementalencoder(encoding)()
519
520 def writerow(self, row):
521 self.writer.writerow([s.encode("utf-8") for s in row])
522 # Fetch UTF-8 output from the queue ...
523 data = self.queue.getvalue()
524 data = data.decode("utf-8")
525 # ... and reencode it into the target encoding
526 data = self.encoder.encode(data)
527 # write to the target stream
528 self.stream.write(data)
529 # empty queue
530 self.queue.truncate(0)
531
532 def writerows(self, rows):
533 for row in rows:
534 self.writerow(row)
535