13.1. csv — CSV File Reading and Writing
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.
所谓CSV(逗号分隔值)格式是电子表格和数据库中最常见的导入和导出格式。这里没有“CSV 标准”,所以格式是由许多读写它的应用操作上定义。这标准上的缺乏意味着细微的差别往往存在于不同的应用程序生产和消费数据。这些差异可以使多个来源的处理CSV文件变得困难。同时,分隔符和引用字符的变化,整体格式如此相似以至于程序员可以写一个单独的模块,此模块可以有效操纵这样的数据,并且封装读写数据的细节。
The csv module implements classes to read and write tabular data in CSVformat. 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.
csv模块实现类读写CSV格式的表格数据。它允许程序员如此说:“Excel优选这种格式写入数据“,或”从Excel等文件读数据,”不知道Excel所用的CSV格式的精确细节,程序员也可以以其他应用程序理解来描述csv格式,或者定义自己专用的csv格式。
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.
csv模块的读写器对象可以读取和写入序列。程序员也可以使用DictReader和DictWriter类读取和写入字典形式的数据。
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.
注意:这个版本(2.7)的csv模块不支持Unicode输入。此外,目前有一些有关于ASCII空字符的问题。因此,所有的输入都应该是UTF-8或者打印安全的ASCII;这些可以在Example部分看实例。
13.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 must be opened with the ‘b’ flag on platforms where that makes a difference. An optionaldialect 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 the Dialect class 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.
返回一个读对象,它会遍历给定的csvfile(可以是支持迭代器协议的任何对象,文件和列表对象都是合适的),每次next()方法调用都会返回一个字符串。如果csvfile是一个文件对象,它必须在有差异的平台上以“b”模式打开文件。一个可选的dialect参数常用来定义一系列特定的csv dialect(不清楚翻译为何为好)参数。它可以是dialect类中的子类或由list_dialects()函数返回的字符串之一的一个实例。其他可选的关键字参数fmtparams可以在当前dialect覆盖个别格式化参数时给出。有关dialect和格式化参数详情,请参照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 >>> with open(‘eggs.csv‘, ‘rb‘) as csvfile: ... spamreader = csv.reader(csvfile, delimiter=‘ ‘, quotechar=‘|‘) ... for row in spamreader: ... print ‘, ‘.join(row) Spam, Spam, Spam, Spam, Spam, Baked BeansSpam Lovely Spam, Wonderful Spam
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.
在2.5版本发生变化:解释器现在相对于多行引述领域更加严格。之前,如果一行结束但没有终止换行符,换行符将插入到返回字段。这种情况经常在读取包含回车符的文件时发生错误。这种情况已被修改,返回字段不会插入新行。因此,如果新行嵌入字段很重要,输入应分成在其中保留换行字符的方式。
- 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 awrite() method. If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference. An optional dialectparameter 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 theDialect class 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 value None is written as the empty string. While this isn’t a reversible transformation, it makes it easier to dump SQL NULL data values toCSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written.
未完待续。。。