blob: 2054ce649ee65bef65c5330f36efc92117587e27 [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
Éric Araujo06176a82012-07-02 17:46:40 -040043 section :ref:`csv-examples`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000044
45
46.. seealso::
47
Georg Brandl8ec7f652007-08-15 14:28:01 +000048 :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
Hynek Schlawack7d978902012-08-28 12:33:46 +020060.. function:: reader(csvfile, dialect='excel', **fmtparams)
Georg Brandl8ec7f652007-08-15 14:28:01 +000061
62 Return a reader object which will iterate over lines in the given *csvfile*.
Georg Brandle7a09902007-10-21 12:10:28 +000063 *csvfile* can be any object which supports the :term:`iterator` protocol and returns a
Georg Brandl9fa61bb2009-07-26 14:19:57 +000064 string each time its :meth:`!next` method is called --- file objects and list
Georg Brandl8ec7f652007-08-15 14:28:01 +000065 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
Hynek Schlawack7d978902012-08-28 12:33:46 +020070 :func:`list_dialects` function. The other optional *fmtparams* keyword arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +000071 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
Skip Montanaro9a1337b2009-03-25 00:52:11 +000075 Each row read from the csv file is returned as a list of strings. No
76 automatic data type conversion is performed.
Georg Brandl8ec7f652007-08-15 14:28:01 +000077
Georg Brandl722e1012007-12-05 17:56:50 +000078 A short usage example::
Georg Brandlc62ef8b2009-01-03 20:55:06 +000079
Georg Brandl722e1012007-12-05 17:56:50 +000080 >>> import csv
Ezio Melottia733d812012-09-15 05:46:24 +030081 >>> with open('eggs.csv', 'rb') as csvfile:
82 ... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
83 ... for row in spamreader:
84 ... print ', '.join(row)
Georg Brandl722e1012007-12-05 17:56:50 +000085 Spam, Spam, Spam, Spam, Spam, Baked Beans
86 Spam, Lovely Spam, Wonderful Spam
87
Georg Brandl8ec7f652007-08-15 14:28:01 +000088 .. versionchanged:: 2.5
89 The parser is now stricter with respect to multi-line quoted fields. Previously,
90 if a line ended within a quoted field without a terminating newline character, a
91 newline would be inserted into the returned field. This behavior caused problems
92 when reading files which contained carriage return characters within fields.
93 The behavior was changed to return the field without inserting newlines. As a
94 consequence, if newlines embedded within fields are important, the input should
95 be split into lines in a manner which preserves the newline characters.
96
97
Hynek Schlawack7d978902012-08-28 12:33:46 +020098.. function:: writer(csvfile, dialect='excel', **fmtparams)
Georg Brandl8ec7f652007-08-15 14:28:01 +000099
100 Return a writer object responsible for converting the user's data into delimited
101 strings on the given file-like object. *csvfile* can be any object with a
102 :func:`write` method. If *csvfile* is a file object, it must be opened with the
103 'b' flag on platforms where that makes a difference. An optional *dialect*
104 parameter can be given which is used to define a set of parameters specific to a
105 particular CSV dialect. It may be an instance of a subclass of the
106 :class:`Dialect` class or one of the strings returned by the
Hynek Schlawack7d978902012-08-28 12:33:46 +0200107 :func:`list_dialects` function. The other optional *fmtparams* keyword arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108 can be given to override individual formatting parameters in the current
109 dialect. For full details about the dialect and formatting parameters, see
110 section :ref:`csv-fmt-params`. To make it
111 as easy as possible to interface with modules which implement the DB API, the
112 value :const:`None` is written as the empty string. While this isn't a
113 reversible transformation, it makes it easier to dump SQL NULL data values to
114 CSV files without preprocessing the data returned from a ``cursor.fetch*`` call.
115 All other non-string data are stringified with :func:`str` before being written.
116
Georg Brandl722e1012007-12-05 17:56:50 +0000117 A short usage example::
118
Ezio Melottia733d812012-09-15 05:46:24 +0300119 import csv
120 with open('eggs.csv', 'wb') as csvfile:
121 spamwriter = csv.writer(csvfile, delimiter=' ',
122 quotechar='|', quoting=csv.QUOTE_MINIMAL)
123 spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
124 spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Georg Brandl722e1012007-12-05 17:56:50 +0000125
Georg Brandl8ec7f652007-08-15 14:28:01 +0000126
Hynek Schlawack7d978902012-08-28 12:33:46 +0200127.. function:: register_dialect(name[, dialect], **fmtparams)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128
129 Associate *dialect* with *name*. *name* must be a string or Unicode object. The
130 dialect can be specified either by passing a sub-class of :class:`Dialect`, or
Hynek Schlawack7d978902012-08-28 12:33:46 +0200131 by *fmtparams* keyword arguments, or both, with keyword arguments overriding
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132 parameters of the dialect. For full details about the dialect and formatting
133 parameters, see section :ref:`csv-fmt-params`.
134
135
136.. function:: unregister_dialect(name)
137
138 Delete the dialect associated with *name* from the dialect registry. An
139 :exc:`Error` is raised if *name* is not a registered dialect name.
140
141
142.. function:: get_dialect(name)
143
144 Return the dialect associated with *name*. An :exc:`Error` is raised if *name*
145 is not a registered dialect name.
146
Skip Montanarod469ff12007-11-04 15:56:52 +0000147 .. versionchanged:: 2.5
Georg Brandl9c466ba2007-11-04 17:43:49 +0000148 This function now returns an immutable :class:`Dialect`. Previously an
149 instance of the requested dialect was returned. Users could modify the
150 underlying class, changing the behavior of active readers and writers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151
152.. function:: list_dialects()
153
154 Return the names of all registered dialects.
155
156
157.. function:: field_size_limit([new_limit])
158
159 Returns the current maximum field size allowed by the parser. If *new_limit* is
160 given, this becomes the new limit.
161
162 .. versionadded:: 2.5
163
164The :mod:`csv` module defines the following classes:
165
166
R David Murray17a43222014-02-24 15:36:45 -0500167.. class:: DictReader(csvfile, fieldnames=None, restkey=None, restval=None, \
168 dialect='excel', *args, **kwds)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169
R David Murray17a43222014-02-24 15:36:45 -0500170 Create an object which operates like a regular reader but maps the
171 information read into a dict whose keys are given by the optional
172 *fieldnames* parameter. The *fieldnames* parameter is a :ref:`sequence
R David Murrayd2b5b312014-02-24 15:35:19 -0500173 <collections-abstract-base-classes>` whose elements are associated with the
174 fields of the input data in order. These elements become the keys of the
R David Murray17a43222014-02-24 15:36:45 -0500175 resulting dictionary. If the *fieldnames* parameter is omitted, the values
176 in the first row of the *csvfile* will be used as the fieldnames. If the
177 row read has more fields than the fieldnames sequence, the remaining data is
178 added as a sequence keyed by the value of *restkey*. If the row read has
179 fewer fields than the fieldnames sequence, the remaining keys take the value
180 of the optional *restval* parameter. Any other optional or keyword
181 arguments are passed to the underlying :class:`reader` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183
R David Murray17a43222014-02-24 15:36:45 -0500184.. class:: DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', \
185 dialect='excel', *args, **kwds)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000186
R David Murray17a43222014-02-24 15:36:45 -0500187 Create an object which operates like a regular writer but maps dictionaries
188 onto output rows. The *fieldnames* parameter is a :ref:`sequence
R David Murrayd2b5b312014-02-24 15:35:19 -0500189 <collections-abstract-base-classes>` of keys that identify the order in
R David Murray17a43222014-02-24 15:36:45 -0500190 which values in the dictionary passed to the :meth:`writerow` method are
191 written to the *csvfile*. The optional *restval* parameter specifies the
192 value to be written if the dictionary is missing a key in *fieldnames*. If
193 the dictionary passed to the :meth:`writerow` method contains a key not
194 found in *fieldnames*, the optional *extrasaction* parameter indicates what
195 action to take. If it is set to ``'raise'`` a :exc:`ValueError` is raised.
196 If it is set to ``'ignore'``, extra values in the dictionary are ignored.
197 Any other optional or keyword arguments are passed to the underlying
198 :class:`writer` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000199
R David Murray17a43222014-02-24 15:36:45 -0500200 Note that unlike the :class:`DictReader` class, the *fieldnames* parameter
201 of the :class:`DictWriter` is not optional. Since Python's :class:`dict`
202 objects are not ordered, there is not enough information available to deduce
203 the order in which the row should be written to the *csvfile*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204
205
206.. class:: Dialect
207
208 The :class:`Dialect` class is a container class relied on primarily for its
209 attributes, which are used to define the parameters for a specific
210 :class:`reader` or :class:`writer` instance.
211
212
213.. class:: excel()
214
215 The :class:`excel` class defines the usual properties of an Excel-generated CSV
216 file. It is registered with the dialect name ``'excel'``.
217
218
219.. class:: excel_tab()
220
221 The :class:`excel_tab` class defines the usual properties of an Excel-generated
222 TAB-delimited file. It is registered with the dialect name ``'excel-tab'``.
223
224
225.. class:: Sniffer()
226
227 The :class:`Sniffer` class is used to deduce the format of a CSV file.
228
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000229 The :class:`Sniffer` class provides two methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000230
Hynek Schlawacke58ce012012-05-22 10:27:40 +0200231 .. method:: sniff(sample, delimiters=None)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000232
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000233 Analyze the given *sample* and return a :class:`Dialect` subclass
234 reflecting the parameters found. If the optional *delimiters* parameter
235 is given, it is interpreted as a string containing possible valid
236 delimiter characters.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237
238
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000239 .. method:: has_header(sample)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000241 Analyze the sample text (presumed to be in CSV format) and return
242 :const:`True` if the first row appears to be a series of column headers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000243
Georg Brandl14aaee12008-01-06 16:04:56 +0000244An example for :class:`Sniffer` use::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245
Ezio Melottia733d812012-09-15 05:46:24 +0300246 with open('example.csv', 'rb') as csvfile:
247 dialect = csv.Sniffer().sniff(csvfile.read(1024))
248 csvfile.seek(0)
249 reader = csv.reader(csvfile, dialect)
250 # ... process CSV file contents here ...
Georg Brandl14aaee12008-01-06 16:04:56 +0000251
252
253The :mod:`csv` module defines the following constants:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000254
255.. data:: QUOTE_ALL
256
257 Instructs :class:`writer` objects to quote all fields.
258
259
260.. data:: QUOTE_MINIMAL
261
262 Instructs :class:`writer` objects to only quote those fields which contain
263 special characters such as *delimiter*, *quotechar* or any of the characters in
264 *lineterminator*.
265
266
267.. data:: QUOTE_NONNUMERIC
268
269 Instructs :class:`writer` objects to quote all non-numeric fields.
270
271 Instructs the reader to convert all non-quoted fields to type *float*.
272
273
274.. data:: QUOTE_NONE
275
276 Instructs :class:`writer` objects to never quote fields. When the current
277 *delimiter* occurs in output data it is preceded by the current *escapechar*
278 character. If *escapechar* is not set, the writer will raise :exc:`Error` if
279 any characters that require escaping are encountered.
280
281 Instructs :class:`reader` to perform no special processing of quote characters.
282
283The :mod:`csv` module defines the following exception:
284
285
286.. exception:: Error
287
288 Raised by any of the functions when an error is detected.
289
290
291.. _csv-fmt-params:
292
293Dialects and Formatting Parameters
294----------------------------------
295
296To make it easier to specify the format of input and output records, specific
297formatting parameters are grouped together into dialects. A dialect is a
298subclass of the :class:`Dialect` class having a set of specific methods and a
299single :meth:`validate` method. When creating :class:`reader` or
300:class:`writer` objects, the programmer can specify a string or a subclass of
301the :class:`Dialect` class as the dialect parameter. In addition to, or instead
302of, the *dialect* parameter, the programmer can also specify individual
303formatting parameters, which have the same names as the attributes defined below
304for the :class:`Dialect` class.
305
306Dialects support the following attributes:
307
308
309.. attribute:: Dialect.delimiter
310
311 A one-character string used to separate fields. It defaults to ``','``.
312
313
314.. attribute:: Dialect.doublequote
315
316 Controls how instances of *quotechar* appearing inside a field should be
317 themselves be quoted. When :const:`True`, the character is doubled. When
318 :const:`False`, the *escapechar* is used as a prefix to the *quotechar*. It
319 defaults to :const:`True`.
320
321 On output, if *doublequote* is :const:`False` and no *escapechar* is set,
322 :exc:`Error` is raised if a *quotechar* is found in a field.
323
324
325.. attribute:: Dialect.escapechar
326
327 A one-character string used by the writer to escape the *delimiter* if *quoting*
328 is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* is
329 :const:`False`. On reading, the *escapechar* removes any special meaning from
330 the following character. It defaults to :const:`None`, which disables escaping.
331
332
333.. attribute:: Dialect.lineterminator
334
335 The string used to terminate lines produced by the :class:`writer`. It defaults
336 to ``'\r\n'``.
337
338 .. note::
339
340 The :class:`reader` is hard-coded to recognise either ``'\r'`` or ``'\n'`` as
341 end-of-line, and ignores *lineterminator*. This behavior may change in the
342 future.
343
344
345.. attribute:: Dialect.quotechar
346
347 A one-character string used to quote fields containing special characters, such
348 as the *delimiter* or *quotechar*, or which contain new-line characters. It
349 defaults to ``'"'``.
350
351
352.. attribute:: Dialect.quoting
353
354 Controls when quotes should be generated by the writer and recognised by the
355 reader. It can take on any of the :const:`QUOTE_\*` constants (see section
356 :ref:`csv-contents`) and defaults to :const:`QUOTE_MINIMAL`.
357
358
359.. attribute:: Dialect.skipinitialspace
360
361 When :const:`True`, whitespace immediately following the *delimiter* is ignored.
362 The default is :const:`False`.
363
364
Ezio Melotti355637b2012-11-18 12:55:35 +0200365.. attribute:: Dialect.strict
366
367 When ``True``, raise exception :exc:`Error` on bad CSV input.
368 The default is ``False``.
369
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370Reader Objects
371--------------
372
373Reader objects (:class:`DictReader` instances and objects returned by the
374:func:`reader` function) have the following public methods:
375
376
377.. method:: csvreader.next()
378
379 Return the next row of the reader's iterable object as a list, parsed according
380 to the current dialect.
381
382Reader objects have the following public attributes:
383
384
385.. attribute:: csvreader.dialect
386
387 A read-only description of the dialect in use by the parser.
388
389
390.. attribute:: csvreader.line_num
391
392 The number of lines read from the source iterator. This is not the same as the
393 number of records returned, as records can span multiple lines.
394
395 .. versionadded:: 2.5
396
397
Skip Montanaroa032bf42008-08-08 22:52:51 +0000398DictReader objects have the following public attribute:
399
400
401.. attribute:: csvreader.fieldnames
402
403 If not passed as a parameter when creating the object, this attribute is
404 initialized upon first access or when the first record is read from the
405 file.
406
407 .. versionchanged:: 2.6
408
409
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410Writer Objects
411--------------
412
413:class:`Writer` objects (:class:`DictWriter` instances and objects returned by
414the :func:`writer` function) have the following public methods. A *row* must be
415a sequence of strings or numbers for :class:`Writer` objects and a dictionary
416mapping fieldnames to strings or numbers (by passing them through :func:`str`
417first) for :class:`DictWriter` objects. Note that complex numbers are written
418out surrounded by parens. This may cause some problems for other programs which
419read CSV files (assuming they support complex numbers at all).
420
421
422.. method:: csvwriter.writerow(row)
423
424 Write the *row* parameter to the writer's file object, formatted according to
425 the current dialect.
426
427
428.. method:: csvwriter.writerows(rows)
429
430 Write all the *rows* parameters (a list of *row* objects as described above) to
431 the writer's file object, formatted according to the current dialect.
432
433Writer objects have the following public attribute:
434
435
436.. attribute:: csvwriter.dialect
437
438 A read-only description of the dialect in use by the writer.
439
440
Dirkjan Ochtman86148172010-02-23 21:09:52 +0000441DictWriter objects have the following public method:
442
443
444.. method:: DictWriter.writeheader()
445
446 Write a row with the field names (as specified in the constructor).
447
448 .. versionadded:: 2.7
449
450
Georg Brandl8ec7f652007-08-15 14:28:01 +0000451.. _csv-examples:
452
453Examples
454--------
455
456The simplest example of reading a CSV file::
457
458 import csv
Eli Benderskyec40bab2011-03-13 08:45:19 +0200459 with open('some.csv', 'rb') as f:
460 reader = csv.reader(f)
461 for row in reader:
462 print row
Georg Brandl8ec7f652007-08-15 14:28:01 +0000463
464Reading a file with an alternate format::
465
466 import csv
Eli Benderskyec40bab2011-03-13 08:45:19 +0200467 with open('passwd', 'rb') as f:
468 reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
469 for row in reader:
470 print row
Georg Brandl8ec7f652007-08-15 14:28:01 +0000471
472The corresponding simplest possible writing example is::
473
474 import csv
Eli Benderskyec40bab2011-03-13 08:45:19 +0200475 with open('some.csv', 'wb') as f:
476 writer = csv.writer(f)
477 writer.writerows(someiterable)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000478
479Registering a new dialect::
480
481 import csv
Georg Brandl8ec7f652007-08-15 14:28:01 +0000482 csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
Eli Benderskyec40bab2011-03-13 08:45:19 +0200483 with open('passwd', 'rb') as f:
484 reader = csv.reader(f, 'unixpwd')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000485
486A slightly more advanced use of the reader --- catching and reporting errors::
487
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000488 import csv, sys
Eli Benderskyec40bab2011-03-13 08:45:19 +0200489 filename = 'some.csv'
490 with open(filename, 'rb') as f:
491 reader = csv.reader(f)
492 try:
493 for row in reader:
494 print row
Andrew Svetlov1625d882012-10-30 21:56:43 +0200495 except csv.Error as e:
Eli Benderskyec40bab2011-03-13 08:45:19 +0200496 sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497
498And while the module doesn't directly support parsing strings, it can easily be
499done::
500
501 import csv
502 for row in csv.reader(['one,two,three']):
503 print row
504
505The :mod:`csv` module doesn't directly support reading and writing Unicode, but
506it is 8-bit-clean save for some problems with ASCII NUL characters. So you can
507write functions or classes that handle the encoding and decoding for you as long
508as you avoid encodings like UTF-16 that use NULs. UTF-8 is recommended.
509
Georg Brandlcf3fb252007-10-21 10:52:38 +0000510:func:`unicode_csv_reader` below is a :term:`generator` that wraps :class:`csv.reader`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000511to handle Unicode CSV data (a list of Unicode strings). :func:`utf_8_encoder`
Georg Brandlcf3fb252007-10-21 10:52:38 +0000512is a :term:`generator` that encodes the Unicode strings as UTF-8, one string (or row) at
Georg Brandl8ec7f652007-08-15 14:28:01 +0000513a time. The encoded strings are parsed by the CSV reader, and
514:func:`unicode_csv_reader` decodes the UTF-8-encoded cells back into Unicode::
515
516 import csv
517
518 def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
519 # csv.py doesn't do Unicode; encode temporarily as UTF-8:
520 csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
521 dialect=dialect, **kwargs)
522 for row in csv_reader:
523 # decode UTF-8 back to Unicode, cell by cell:
524 yield [unicode(cell, 'utf-8') for cell in row]
525
526 def utf_8_encoder(unicode_csv_data):
527 for line in unicode_csv_data:
528 yield line.encode('utf-8')
529
530For all other encodings the following :class:`UnicodeReader` and
531:class:`UnicodeWriter` classes can be used. They take an additional *encoding*
532parameter in their constructor and make sure that the data passes the real
533reader or writer encoded as UTF-8::
534
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000535 import csv, codecs, cStringIO
Georg Brandl8ec7f652007-08-15 14:28:01 +0000536
537 class UTF8Recoder:
538 """
539 Iterator that reads an encoded stream and reencodes the input to UTF-8
540 """
541 def __init__(self, f, encoding):
542 self.reader = codecs.getreader(encoding)(f)
543
544 def __iter__(self):
545 return self
546
547 def next(self):
548 return self.reader.next().encode("utf-8")
549
550 class UnicodeReader:
551 """
552 A CSV reader which will iterate over lines in the CSV file "f",
553 which is encoded in the given encoding.
554 """
555
556 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
557 f = UTF8Recoder(f, encoding)
558 self.reader = csv.reader(f, dialect=dialect, **kwds)
559
560 def next(self):
561 row = self.reader.next()
562 return [unicode(s, "utf-8") for s in row]
563
564 def __iter__(self):
565 return self
566
567 class UnicodeWriter:
568 """
569 A CSV writer which will write rows to CSV file "f",
570 which is encoded in the given encoding.
571 """
572
573 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
574 # Redirect output to a queue
575 self.queue = cStringIO.StringIO()
576 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
577 self.stream = f
578 self.encoder = codecs.getincrementalencoder(encoding)()
579
580 def writerow(self, row):
581 self.writer.writerow([s.encode("utf-8") for s in row])
582 # Fetch UTF-8 output from the queue ...
583 data = self.queue.getvalue()
584 data = data.decode("utf-8")
585 # ... and reencode it into the target encoding
586 data = self.encoder.encode(data)
587 # write to the target stream
588 self.stream.write(data)
589 # empty queue
590 self.queue.truncate(0)
591
592 def writerows(self, rows):
593 for row in rows:
594 self.writerow(row)
595