blob: 86d102551e8dc91143140f1830c6f90f67fe3d36 [file] [log] [blame]
Skip Montanarob4a04172003-03-20 23:29:12 +00001\section{\module{csv} --- CSV File Reading and Writing}
2
3\declaremodule{standard}{csv}
4\modulesynopsis{Write and read tabular data to and from delimited files.}
Skip Montanaro3bd3c842003-04-24 18:47:31 +00005\sectionauthor{Skip Montanaro}{skip@pobox.com}
Skip Montanarob4a04172003-03-20 23:29:12 +00006
7\versionadded{2.3}
8\index{csv}
9\indexii{data}{tabular}
10
11The so-called CSV (Comma Separated Values) format is the most common import
12and export format for spreadsheets and databases. There is no ``CSV
13standard'', so the format is operationally defined by the many applications
14which read and write it. The lack of a standard means that subtle
15differences often exist in the data produced and consumed by different
16applications. These differences can make it annoying to process CSV files
17from multiple sources. Still, while the delimiters and quoting characters
18vary, the overall format is similar enough that it is possible to write a
19single module which can efficiently manipulate such data, hiding the details
20of reading and writing the data from the programmer.
21
Skip Montanaro5d0136e2003-04-25 15:14:49 +000022The \module{csv} module implements classes to read and write tabular data in
Skip Montanarob4a04172003-03-20 23:29:12 +000023CSV format. It allows programmers to say, ``write this data in the format
24preferred by Excel,'' or ``read data from this file which was generated by
25Excel,'' without knowing the precise details of the CSV format used by
26Excel. Programmers can also describe the CSV formats understood by other
27applications or define their own special-purpose CSV formats.
28
Skip Montanaro5d0136e2003-04-25 15:14:49 +000029The \module{csv} module's \class{reader} and \class{writer} objects read and
Skip Montanarob4a04172003-03-20 23:29:12 +000030write sequences. Programmers can also read and write data in dictionary
31form using the \class{DictReader} and \class{DictWriter} classes.
32
Fred Drake96352682003-04-25 18:02:34 +000033\begin{notice}
34 This version of the \module{csv} module doesn't support Unicode
35 input. Also, there are currently some issues regarding \ASCII{} NUL
36 characters. Accordingly, all input should generally be printable
37 \ASCII{} to be safe. These restrictions will be removed in the future.
38\end{notice}
Skip Montanarob4a04172003-03-20 23:29:12 +000039
40\begin{seealso}
41% \seemodule{array}{Arrays of uniformly types numeric values.}
42 \seepep{305}{CSV File API}
43 {The Python Enhancement Proposal which proposed this addition
44 to Python.}
45\end{seealso}
46
47
Raymond Hettinger6f6d7b932003-08-31 05:44:54 +000048\subsection{Module Contents \label{csv-contents}}
Skip Montanarob4a04172003-03-20 23:29:12 +000049
Skip Montanaro5d0136e2003-04-25 15:14:49 +000050The \module{csv} module defines the following functions:
Skip Montanarob4a04172003-03-20 23:29:12 +000051
52\begin{funcdesc}{reader}{csvfile\optional{,
Andrew McNamara8231de02005-01-12 11:47:57 +000053 dialect=\code{'excel'}}\optional{, fmtparam}}
Skip Montanarob4a04172003-03-20 23:29:12 +000054Return a reader object which will iterate over lines in the given
55{}\var{csvfile}. \var{csvfile} can be any object which supports the
56iterator protocol and returns a string each time its \method{next}
Andrew McNamara8231de02005-01-12 11:47:57 +000057method is called - file objects and list objects are both suitable.
58If \var{csvfile} is a file object, it must be opened with
Skip Montanaro5e4e39f2003-07-02 15:32:48 +000059the 'b' flag on platforms where that makes a difference. An optional
60{}\var{dialect} parameter can be given
Skip Montanarob4a04172003-03-20 23:29:12 +000061which is used to define a set of parameters specific to a particular CSV
62dialect. It may be an instance of a subclass of the \class{Dialect}
63class or one of the strings returned by the \function{list_dialects}
64function. The other optional {}\var{fmtparam} keyword arguments can be
65given to override individual formatting parameters in the current
66dialect. For more information about the dialect and formatting
Raymond Hettinger6e380cd2003-09-10 18:54:49 +000067parameters, see section~\ref{csv-fmt-params}, ``Dialects and Formatting
Skip Montanarob4a04172003-03-20 23:29:12 +000068Parameters'' for details of these parameters.
69
70All data read are returned as strings. No automatic data type
71conversion is performed.
72\end{funcdesc}
73
74\begin{funcdesc}{writer}{csvfile\optional{,
Andrew McNamara8231de02005-01-12 11:47:57 +000075 dialect=\code{'excel'}}\optional{, fmtparam}}
Skip Montanarob4a04172003-03-20 23:29:12 +000076Return a writer object responsible for converting the user's data into
Skip Montanaro5e4e39f2003-07-02 15:32:48 +000077delimited strings on the given file-like object. \var{csvfile} can be any
78object with a \function{write} method. If \var{csvfile} is a file object,
79it must be opened with the 'b' flag on platforms where that makes a
80difference. An optional
Skip Montanarob4a04172003-03-20 23:29:12 +000081{}\var{dialect} parameter can be given which is used to define a set of
82parameters specific to a particular CSV dialect. It may be an instance
83of a subclass of the \class{Dialect} class or one of the strings
84returned by the \function{list_dialects} function. The other optional
85{}\var{fmtparam} keyword arguments can be given to override individual
86formatting parameters in the current dialect. For more information
87about the dialect and formatting parameters, see
Raymond Hettinger6e380cd2003-09-10 18:54:49 +000088section~\ref{csv-fmt-params}, ``Dialects and Formatting Parameters'' for
Skip Montanarob4a04172003-03-20 23:29:12 +000089details of these parameters. To make it as easy as possible to
90interface with modules which implement the DB API, the value
91\constant{None} is written as the empty string. While this isn't a
92reversible transformation, it makes it easier to dump SQL NULL data values
93to CSV files without preprocessing the data returned from a
94\code{cursor.fetch*()} call. All other non-string data are stringified
95with \function{str()} before being written.
96\end{funcdesc}
97
Andrew McNamara8231de02005-01-12 11:47:57 +000098\begin{funcdesc}{register_dialect}{name\optional{, dialect}\optional{, fmtparam}}
99Associate \var{dialect} with \var{name}. \var{name} must be a string
100or Unicode object. The dialect can be specified either by passing a
101sub-class of \class{Dialect}, or by \var{fmtparam} keyword arguments,
102or both, with keyword arguments overriding parameters of the dialect.
103For more information about the dialect and formatting parameters, see
104section~\ref{csv-fmt-params}, ``Dialects and Formatting Parameters''
105for details of these parameters.
Skip Montanarob4a04172003-03-20 23:29:12 +0000106\end{funcdesc}
107
108\begin{funcdesc}{unregister_dialect}{name}
109Delete the dialect associated with \var{name} from the dialect registry. An
110\exception{Error} is raised if \var{name} is not a registered dialect
111name.
112\end{funcdesc}
113
114\begin{funcdesc}{get_dialect}{name}
115Return the dialect associated with \var{name}. An \exception{Error} is
116raised if \var{name} is not a registered dialect name.
117\end{funcdesc}
118
119\begin{funcdesc}{list_dialects}{}
120Return the names of all registered dialects.
121\end{funcdesc}
122
Andrew McNamara8231de02005-01-12 11:47:57 +0000123\begin{funcdesc}{field_size_limit}{\optional{new_limit}}
124 Returns the current maximum field size allowed by the parser. If
125 \var{new_limit} is given, this becomes the new limit.
126 \versionadded{2.5}
127\end{funcdesc}
128
Skip Montanarob4a04172003-03-20 23:29:12 +0000129
Skip Montanaro5d0136e2003-04-25 15:14:49 +0000130The \module{csv} module defines the following classes:
Skip Montanarob4a04172003-03-20 23:29:12 +0000131
Skip Montanarodffeed32003-10-03 14:03:01 +0000132\begin{classdesc}{DictReader}{csvfile\optional{,
133 fieldnames=\constant{None},\optional{,
Fred Drake96352682003-04-25 18:02:34 +0000134 restkey=\constant{None}\optional{,
135 restval=\constant{None}\optional{,
Skip Montanarob4a04172003-03-20 23:29:12 +0000136 dialect=\code{'excel'}\optional{,
Skip Montanaro10659f22004-04-16 03:21:01 +0000137 *args, **kwds}}}}}}
Skip Montanarob4a04172003-03-20 23:29:12 +0000138Create an object which operates like a regular reader but maps the
Skip Montanarodffeed32003-10-03 14:03:01 +0000139information read into a dict whose keys are given by the optional
140{} \var{fieldnames}
141parameter. If the \var{fieldnames} parameter is omitted, the values in
142the first row of the \var{csvfile} will be used as the fieldnames.
143If the row read has fewer fields than the fieldnames sequence,
Skip Montanarob4a04172003-03-20 23:29:12 +0000144the value of \var{restval} will be used as the default value. If the row
145read has more fields than the fieldnames sequence, the remaining data is
146added as a sequence keyed by the value of \var{restkey}. If the row read
147has fewer fields than the fieldnames sequence, the remaining keys take the
Skip Montanaro10659f22004-04-16 03:21:01 +0000148value of the optional \var{restval} parameter. Any other optional or
149keyword arguments are passed to the underlying \class{reader} instance.
Skip Montanarob4a04172003-03-20 23:29:12 +0000150\end{classdesc}
151
152
153\begin{classdesc}{DictWriter}{csvfile, fieldnames\optional{,
154 restval=""\optional{,
155 extrasaction=\code{'raise'}\optional{,
Skip Montanaro10659f22004-04-16 03:21:01 +0000156 dialect=\code{'excel'}\optional{,
157 *args, **kwds}}}}}
Skip Montanarob4a04172003-03-20 23:29:12 +0000158Create an object which operates like a regular writer but maps dictionaries
159onto output rows. The \var{fieldnames} parameter identifies the order in
160which values in the dictionary passed to the \method{writerow()} method are
161written to the \var{csvfile}. The optional \var{restval} parameter
162specifies the value to be written if the dictionary is missing a key in
163\var{fieldnames}. If the dictionary passed to the \method{writerow()}
164method contains a key not found in \var{fieldnames}, the optional
165\var{extrasaction} parameter indicates what action to take. If it is set
166to \code{'raise'} a \exception{ValueError} is raised. If it is set to
Skip Montanaro10659f22004-04-16 03:21:01 +0000167\code{'ignore'}, extra values in the dictionary are ignored. Any other
168optional or keyword arguments are passed to the underlying \class{writer}
169instance.
Skip Montanarodffeed32003-10-03 14:03:01 +0000170
171Note that unlike the \class{DictReader} class, the \var{fieldnames}
172parameter of the \class{DictWriter} is not optional. Since Python's
173\class{dict} objects are not ordered, there is not enough information
174available to deduce the order in which the row should be written to the
175\var{csvfile}.
176
Skip Montanarob4a04172003-03-20 23:29:12 +0000177\end{classdesc}
178
Skip Montanarob4a04172003-03-20 23:29:12 +0000179\begin{classdesc*}{Dialect}{}
180The \class{Dialect} class is a container class relied on primarily for its
181attributes, which are used to define the parameters for a specific
Fred Drake96352682003-04-25 18:02:34 +0000182\class{reader} or \class{writer} instance.
Skip Montanarob4a04172003-03-20 23:29:12 +0000183\end{classdesc*}
184
Skip Montanarobb0c9dc2005-01-05 06:58:15 +0000185\begin{classdesc}{excel}{}
186The \class{excel} class defines the usual properties of an Excel-generated
187CSV file.
188\end{classdesc}
189
190\begin{classdesc}{excel_tab}{}
191The \class{excel_tab} class defines the usual properties of an
192Excel-generated TAB-delimited file.
193\end{classdesc}
194
Skip Montanaro77892372003-05-19 15:33:36 +0000195\begin{classdesc}{Sniffer}{}
196The \class{Sniffer} class is used to deduce the format of a CSV file.
Fred Drake96352682003-04-25 18:02:34 +0000197\end{classdesc}
198
Skip Montanaro8bdaac72005-12-28 15:56:58 +0000199The \class{Sniffer} class provides two methods:
Fred Drake96352682003-04-25 18:02:34 +0000200
Skip Montanaro77892372003-05-19 15:33:36 +0000201\begin{methoddesc}{sniff}{sample\optional{,delimiters=None}}
202Analyze the given \var{sample} and return a \class{Dialect} subclass
203reflecting the parameters found. If the optional \var{delimiters} parameter
204is given, it is interpreted as a string containing possible valid delimiter
205characters.
Fred Drake96352682003-04-25 18:02:34 +0000206\end{methoddesc}
207
208\begin{methoddesc}{has_header}{sample}
209Analyze the sample text (presumed to be in CSV format) and return
210\constant{True} if the first row appears to be a series of column
211headers.
212\end{methoddesc}
213
214
Skip Montanarob4a04172003-03-20 23:29:12 +0000215The \module{csv} module defines the following constants:
216
Skip Montanaroa1045562003-06-04 15:30:13 +0000217\begin{datadesc}{QUOTE_ALL}
Skip Montanarob4a04172003-03-20 23:29:12 +0000218Instructs \class{writer} objects to quote all fields.
219\end{datadesc}
220
221\begin{datadesc}{QUOTE_MINIMAL}
222Instructs \class{writer} objects to only quote those fields which contain
Andrew McNamara8231de02005-01-12 11:47:57 +0000223special characters such as \var{delimiter}, \var{quotechar} or any of the
224characters in \var{lineterminator}.
Skip Montanarob4a04172003-03-20 23:29:12 +0000225\end{datadesc}
226
227\begin{datadesc}{QUOTE_NONNUMERIC}
Andrew McNamara8231de02005-01-12 11:47:57 +0000228Instructs \class{writer} objects to quote all non-numeric
229fields.
230
231Instructs the reader to convert all non-quoted fields to type \var{float}.
Skip Montanarob4a04172003-03-20 23:29:12 +0000232\end{datadesc}
233
234\begin{datadesc}{QUOTE_NONE}
235Instructs \class{writer} objects to never quote fields. When the current
236\var{delimiter} occurs in output data it is preceded by the current
Andrew McNamara8231de02005-01-12 11:47:57 +0000237\var{escapechar} character. If \var{escapechar} is not set, the writer
238will raise \exception{Error} if any characters that require escaping
239are encountered.
240
241Instructs \class{reader} to perform no special processing of quote characters.
Skip Montanarob4a04172003-03-20 23:29:12 +0000242\end{datadesc}
243
244
245The \module{csv} module defines the following exception:
246
247\begin{excdesc}{Error}
248Raised by any of the functions when an error is detected.
249\end{excdesc}
250
251
Fred Drake96352682003-04-25 18:02:34 +0000252\subsection{Dialects and Formatting Parameters\label{csv-fmt-params}}
Skip Montanarob4a04172003-03-20 23:29:12 +0000253
254To make it easier to specify the format of input and output records,
255specific formatting parameters are grouped together into dialects. A
256dialect is a subclass of the \class{Dialect} class having a set of specific
257methods and a single \method{validate()} method. When creating \class{reader}
258or \class{writer} objects, the programmer can specify a string or a subclass
259of the \class{Dialect} class as the dialect parameter. In addition to, or
260instead of, the \var{dialect} parameter, the programmer can also specify
261individual formatting parameters, which have the same names as the
Raymond Hettinger6f6d7b932003-08-31 05:44:54 +0000262attributes defined below for the \class{Dialect} class.
Skip Montanarob4a04172003-03-20 23:29:12 +0000263
Fred Drake96352682003-04-25 18:02:34 +0000264Dialects support the following attributes:
265
266\begin{memberdesc}[Dialect]{delimiter}
267A one-character string used to separate fields. It defaults to \code{','}.
268\end{memberdesc}
269
270\begin{memberdesc}[Dialect]{doublequote}
Andrew McNamara8231de02005-01-12 11:47:57 +0000271Controls how instances of \var{quotechar} appearing inside a field should
272be themselves be quoted. When \constant{True}, the character is doubled.
273When \constant{False}, the \var{escapechar} is used as a prefix to the
274\var{quotechar}. It defaults to \constant{True}.
275
276On output, if \var{doublequote} is \constant{False} and no
277\var{escapechar} is set, \exception{Error} is raised if a \var{quotechar}
278is found in a field.
Fred Drake96352682003-04-25 18:02:34 +0000279\end{memberdesc}
280
281\begin{memberdesc}[Dialect]{escapechar}
Andrew McNamara8231de02005-01-12 11:47:57 +0000282A one-character string used by the writer to escape the \var{delimiter} if
283\var{quoting} is set to \constant{QUOTE_NONE} and the \var{quotechar}
284if \var{doublequote} is \constant{False}. On reading, the \var{escapechar}
285removes any special meaning from the following character. It defaults
286to \constant{None}, which disables escaping.
Fred Drake96352682003-04-25 18:02:34 +0000287\end{memberdesc}
288
289\begin{memberdesc}[Dialect]{lineterminator}
Andrew McNamara8231de02005-01-12 11:47:57 +0000290The string used to terminate lines produced by the \class{writer}.
291It defaults to \code{'\e r\e n'}.
292
293\note{The \class{reader} is hard-coded to recognise either \code{'\e r'}
294or \code{'\e n'} as end-of-line, and ignores \var{lineterminator}. This
295behavior may change in the future.}
Fred Drake96352682003-04-25 18:02:34 +0000296\end{memberdesc}
297
298\begin{memberdesc}[Dialect]{quotechar}
Andrew McNamara8231de02005-01-12 11:47:57 +0000299A one-character string used to quote fields containing special characters,
300such as the \var{delimiter} or \var{quotechar}, or which contain new-line
301characters. It defaults to \code{'"'}.
Fred Drake96352682003-04-25 18:02:34 +0000302\end{memberdesc}
303
304\begin{memberdesc}[Dialect]{quoting}
Andrew McNamara8231de02005-01-12 11:47:57 +0000305Controls when quotes should be generated by the writer and recognised
306by the reader. It can take on any of the \constant{QUOTE_*} constants
307(see section~\ref{csv-contents}) and defaults to \constant{QUOTE_MINIMAL}.
Fred Drake96352682003-04-25 18:02:34 +0000308\end{memberdesc}
309
310\begin{memberdesc}[Dialect]{skipinitialspace}
311When \constant{True}, whitespace immediately following the \var{delimiter}
312is ignored. The default is \constant{False}.
313\end{memberdesc}
314
Skip Montanarob4a04172003-03-20 23:29:12 +0000315
316\subsection{Reader Objects}
317
Fred Drake96352682003-04-25 18:02:34 +0000318Reader objects (\class{DictReader} instances and objects returned by
Raymond Hettinger6f6d7b932003-08-31 05:44:54 +0000319the \function{reader()} function) have the following public methods:
Skip Montanarob4a04172003-03-20 23:29:12 +0000320
Fred Drake96352682003-04-25 18:02:34 +0000321\begin{methoddesc}[csv reader]{next}{}
Skip Montanarob4a04172003-03-20 23:29:12 +0000322Return the next row of the reader's iterable object as a list, parsed
323according to the current dialect.
324\end{methoddesc}
325
Andrew McNamara8231de02005-01-12 11:47:57 +0000326Reader objects have the following public attributes:
327
328\begin{memberdesc}[csv reader]{dialect}
329A read-only description of the dialect in use by the parser.
330\end{memberdesc}
331
332\begin{memberdesc}[csv reader]{line_num}
333 The number of lines read from the source iterator. This is not the same
334 as the number of records returned, as records can span multiple lines.
335\end{memberdesc}
336
Skip Montanarob4a04172003-03-20 23:29:12 +0000337
338\subsection{Writer Objects}
339
Skip Montanaroba0485a2004-01-21 13:47:04 +0000340\class{Writer} objects (\class{DictWriter} instances and objects returned by
341the \function{writer()} function) have the following public methods. A
342{}\var{row} must be a sequence of strings or numbers for \class{Writer}
343objects and a dictionary mapping fieldnames to strings or numbers (by
344passing them through \function{str()} first) for {}\class{DictWriter}
345objects. Note that complex numbers are written out surrounded by parens.
346This may cause some problems for other programs which read CSV files
347(assuming they support complex numbers at all).
Skip Montanarob4a04172003-03-20 23:29:12 +0000348
Fred Drake96352682003-04-25 18:02:34 +0000349\begin{methoddesc}[csv writer]{writerow}{row}
Skip Montanarob4a04172003-03-20 23:29:12 +0000350Write the \var{row} parameter to the writer's file object, formatted
351according to the current dialect.
352\end{methoddesc}
353
Fred Drake96352682003-04-25 18:02:34 +0000354\begin{methoddesc}[csv writer]{writerows}{rows}
Skip Montanaroba0485a2004-01-21 13:47:04 +0000355Write all the \var{rows} parameters (a list of \var{row} objects as
356described above) to the writer's file object, formatted
Skip Montanarob4a04172003-03-20 23:29:12 +0000357according to the current dialect.
358\end{methoddesc}
359
Andrew McNamara8231de02005-01-12 11:47:57 +0000360Writer objects have the following public attribute:
361
362\begin{memberdesc}[csv writer]{dialect}
363A read-only description of the dialect in use by the writer.
364\end{memberdesc}
365
366
Skip Montanarob4a04172003-03-20 23:29:12 +0000367
368\subsection{Examples}
369
Andrew McNamara8231de02005-01-12 11:47:57 +0000370The simplest example of reading a CSV file:
Skip Montanarob4a04172003-03-20 23:29:12 +0000371
372\begin{verbatim}
Fred Drake96352682003-04-25 18:02:34 +0000373import csv
Andrew M. Kuchling6f937b12004-08-07 15:11:24 +0000374reader = csv.reader(open("some.csv", "rb"))
Fred Drake96352682003-04-25 18:02:34 +0000375for row in reader:
376 print row
Skip Montanarob4a04172003-03-20 23:29:12 +0000377\end{verbatim}
378
Andrew McNamara8231de02005-01-12 11:47:57 +0000379Reading a file with an alternate format:
Skip Montanaro2b2795a2004-07-08 19:49:10 +0000380
381\begin{verbatim}
382import csv
Andrew McNamara8231de02005-01-12 11:47:57 +0000383reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
Skip Montanaro2b2795a2004-07-08 19:49:10 +0000384for row in reader:
Andrew McNamara8231de02005-01-12 11:47:57 +0000385 print row
Skip Montanaro2b2795a2004-07-08 19:49:10 +0000386\end{verbatim}
387
Andrew McNamara8231de02005-01-12 11:47:57 +0000388The corresponding simplest possible writing example is:
Skip Montanarob4a04172003-03-20 23:29:12 +0000389
390\begin{verbatim}
Fred Drake96352682003-04-25 18:02:34 +0000391import csv
Andrew M. Kuchling6f937b12004-08-07 15:11:24 +0000392writer = csv.writer(open("some.csv", "wb"))
Andrew McNamara8231de02005-01-12 11:47:57 +0000393writer.writerows(someiterable)
Skip Montanarob4a04172003-03-20 23:29:12 +0000394\end{verbatim}
Andrew McNamara8231de02005-01-12 11:47:57 +0000395
396Registering a new dialect:
397
398\begin{verbatim}
399import csv
400
401csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
402
403reader = csv.reader(open("passwd", "rb"), 'unixpwd')
404\end{verbatim}
405
406A slightly more advanced use of the reader - catching and reporting errors:
407
408\begin{verbatim}
409import csv, sys
410filename = "some.csv"
411reader = csv.reader(open(filename, "rb"))
412try:
413 for row in reader:
414 print row
415except csv.Error, e:
416 sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
417\end{verbatim}
418
419And while the module doesn't directly support parsing strings, it can
420easily be done:
421
422\begin{verbatim}
423import csv
424print csv.reader(['one,two,three'])[0]
425\end{verbatim}
426
Skip Montanaro5011c3f2005-03-18 16:56:37 +0000427The \module{csv} module doesn't directly support reading and writing
428Unicode, but it is 8-bit clean save for some problems with \ASCII{} NUL
429characters, so you can write classes that handle the encoding and decoding
430for you as long as you avoid encodings like utf-16 that use NULs.
431
432\begin{verbatim}
433import csv
434
435class UnicodeReader:
436 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
437 self.reader = csv.reader(f, dialect=dialect, **kwds)
438 self.encoding = encoding
439
440 def next(self):
441 row = self.reader.next()
442 return [unicode(s, self.encoding) for s in row]
443
444 def __iter__(self):
445 return self
446
447class UnicodeWriter:
448 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
449 self.writer = csv.writer(f, dialect=dialect, **kwds)
450 self.encoding = encoding
451
452 def writerow(self, row):
453 self.writer.writerow([s.encode("utf-8") for s in row])
454
455 def writerows(self, rows):
456 for row in rows:
457 self.writerow(row)
458\end{verbatim}
459
460They should work just like the \class{csv.reader} and \class{csv.writer}
461classes but add an \var{encoding} parameter.