The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There is no “CSV standard”, so the format is operationally defined by the many applications which read and write it. The lack of a standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.
The csv module implements classes to read and write tabular data in CSV
format. It allows programmers to say, “write this data in the format preferred
by Excel,” or “read data from this file which was generated by Excel,” without
knowing the precise details of the CSV format used by Excel. Programmers can
also describe the CSV formats understood by other applications or define their
own special-purpose CSV formats.
The csv module’s reader and writer objects read and
write sequences. Programmers can also read and write data in dictionary form
using the DictReader and DictWriter classes.
Note
This version of the csv module doesn’t support Unicode input. Also,
there are currently some issues regarding ASCII NUL characters. Accordingly,
all input should be UTF-8 or printable ASCII to be safe; see the examples in
section Examples. These restrictions will be removed in the future.
See also
- PEP 305 - CSV File API
- The Python Enhancement Proposal which proposed this addition to Python.
13.1.1. Module Contents¶
The csv module defines the following functions:
-
csv.reader(csvfile[, dialect='excel'][, fmtparam])¶ Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its
next()method is called — file objects and list objects are both suitable. If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference. An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of theDialectclass or one of the strings returned by thelist_dialects()function. The other optional fmtparam keyword arguments can be given to override individual formatting parameters in the current dialect. For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters.Each row read from the csv file is returned as a list of strings. No automatic data type conversion is performed.
A short usage example:
>>> import csv >>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|') >>> for row in spamReader: ... print ', '.join(row) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam
Changed in version 2.5:
Changed in version 2.5: The parser is now stricter with respect to multi-line quoted fields. Previously, if a line ended within a quoted field without a terminating newline character, a newline would be inserted into the returned field. This behavior caused problems when reading files which contained carriage return characters within fields. The behavior was changed to return the field without inserting newlines. As a consequence, if newlines embedded within fields are important, the input should be split into lines in a manner which preserves the newline characters.
-
csv.writer(csvfile[, dialect='excel'][, fmtparam])¶ Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a
write()method. If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference. An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of theDialectclass or one of the strings returned by thelist_dialects()function. The other optional fmtparam keyword arguments can be given to override individual formatting parameters in the current dialect. For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters. To make it as easy as possible to interface with modules which implement the DB API, the valueNoneis written as the empty string. While this isn’t a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from acursor.fetch*call. All other non-string data are stringified withstr()before being written.A short usage example:
>>> import csv >>> spamWriter = csv.writer(open('eggs.csv', 'wb'), delimiter=' ', ... quotechar='|', quoting=csv.QUOTE_MINIMAL) >>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans']) >>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
-
csv.register_dialect(name[, dialect][, fmtparam])¶ Associate dialect with name. name must be a string or Unicode object. The dialect can be specified either by passing a sub-class of
Dialect, or by fmtparam keyword arguments, or both, with keyword arguments overriding parameters of the dialect. For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters.
-
csv.unregister_dialect(name)¶ Delete the dialect associated with name from the dialect registry. An
Erroris raised if name is not a registered dialect name.
-
csv.get_dialect(name)¶ Return the dialect associated with name. An
Erroris raised if name is not a registered dialect name.Changed in version 2.5:
Changed in version 2.5: This function now returns an immutable
Dialect. Previously an instance of the requested dialect was returned. Users could modify the underlying class, changing the behavior of active readers and writers.