14.1. csv — CSV File Reading and Writing¶
Source code: Lib/csv.py
The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180. The lack of a well-defined 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.
也參考
- PEP 305 - CSV File API
- The Python Enhancement Proposal which proposed this addition to Python.
14.1.1. Module Contents¶
The csv module defines the following functions:
-
csv.reader(csvfile, dialect='excel', **fmtparams)¶ 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 should be opened withnewline=''. [1] 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 fmtparams 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 unless the
QUOTE_NONNUMERICformat option is specified (in which case unquoted fields are transformed into floats).A short usage example:
>>> import csv >>> with open('eggs.csv', newline='') as csvfile: ... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') ... for row in spamreader: ... print(', '.join(row)) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam
-
csv.writer(csvfile, dialect='excel', **fmtparams)¶ 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 should be opened withnewline=''[1]. 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 fmtparams 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 with open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
-
csv.register_dialect(name[, dialect[, **fmtparams]])¶ Associate dialect with name. name must be a string. The dialect can be specified either by passing a sub-class of
Dialect, or by fmtparams 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. This function returns an immutableDialect.
-
csv.list_dialects()¶ Return the names of all registered dialects.
-
csv.field_size_limit([new_limit])¶ Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.
The csv module defines the following classes:
-
class
csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)¶ Create an object that operates like a regular reader but maps the information in each row to an
OrderedDictwhose keys are given by the optional fieldnames parameter.The fieldnames parameter is a sequence. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames. Regardless of how the fieldnames are determined, the ordered dictionary preserves their original ordering.
If a row has more fields than fieldnames, the remaining data is put in a list and stored with the fieldname specified by restkey (which defaults to
None). If a non-blank row has fewer fields than fieldnames, the missing values are filled-in withNone.All other optional or keyword arguments are passed to the underlying
readerinstance.3.6 版更變: Returned rows are now of type
OrderedDict.A short usage example:
>>> import csv >>> with open('names.csv', newline='') as csvfile: ... reader = csv.DictReader(csvfile) ... for row in reader: ... print(row['first_name'], row['last_name']) ... Eric Idle John Cleese >>> print(row) OrderedDict([('first_name', 'John'), ('last_name', 'Cleese')])
-
class
csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)¶ Create an object which operates like a regular writer but maps dictionaries onto output rows. The fieldnames parameter is a
sequenceof keys that identify the order in which values in the dictionary passed to thewriterow()method are written to file f. The optional restval parameter specifies the value to be written if the dictionary is missing a key in fieldnames. If the dictionary passed to thewriterow()method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to'raise', the default value, aValueErroris raised. If it is set to'ignore', extra values in the dictionary are ignored. Any other optional or keyword arguments are passed to the underlyingwriterinstance.Note that unlike the
DictReaderclass, the fieldnames parameter of theDictWriterclass is not optional.A short usage example:
import csv with open('names.csv', 'w', newline='') as csvfile: fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
-
class
csv.Dialect¶ The
Dialectclass is a container class relied on primarily for its attributes, which are used to define the parameters for a specificreaderorwriterinstance.
-
class
csv.excel¶ The
excelclass defines the usual properties of an Excel-generated CSV file. It is registered with the dialect name'excel'.
-
class
csv.excel_tab¶ The
excel_tabclass defines the usual properties of an Excel-generated TAB-delimited file. It is registered with the dialect name'excel-tab'.
-
class
csv.unix_dialect¶ The
unix_dialectclass defines the usual properties of a CSV file generated on UNIX systems, i.e. using'\n'as line terminator and quoting all fields. It is registered with the dialect name'unix'.3.2 版新加入.
-
class
csv.Sniffer¶ The
Snifferclass is used to deduce the format of a CSV file.The
Snifferclass provides two methods:
An example for Sniffer use:
with open('example.csv', newline='') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
