/Doc/library/csv.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 569 lines · 379 code · 190 blank · 0 comment · 0 complexity · 9fe3fca22819a9726beea58ad4a32db0 MD5 · raw file

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