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