csv
— CSV File Reading and WritingCSV文件读写¶
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(逗号分隔值)格式是电子表格和数据库最常见的导入和导出格式。CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180. 在RFC 4180中试图以标准化的方式描述CSV格式之前,CSV格式已使用多年。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. 这些差异会使处理来自多个源的CSV文件变得烦人。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模块实现了以csv
module implements classes to read and write tabular data in CSV format. csv
格式读写表格数据的类。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. 它允许程序员说,“以Excel首选的格式写入数据”或“从Excel生成的文件中读取数据”,而不知道Excel使用的CSV格式的确切细节。Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats.程序员还可以描述其他应用程序理解的CSV格式,或定义自己的专用CSV格式。
The csv
module’s reader
and writer
objects read and write sequences. csv
模块的reader
和writer
对象读写序列。Programmers can also read and write data in dictionary form using the 程序员还可以使用DictReader
and DictWriter
classes.DictReader
和DictWriter
类以字典形式读写数据。
See also
- PEP 305 - CSV File API
The Python Enhancement Proposal which proposed this addition to Python.Python增强方案提出了对Python的这一添加。
Module Contents模块内容¶
The csv
module defines the following functions:csv
模块定义了以下功能:
-
csv.
reader
(csvfile, dialect='excel', **fmtparams)¶ Return a reader object which will iterate over lines in the given csvfile.返回一个读卡器对象,该对象将迭代给定csvfile中的行。csvfile can be any object which supports the iterator protocol and returns a string each time itscsvfile可以是任何支持迭代器协议的对象,并且每次调用其__next__()
method is called — file objects and list objects are both suitable.__next__()
方法时都返回一个字符串-文件对象和列表对象都适用。If csvfile is a file object, it should be opened with如果csvfile是文件对象,则应使用newline=''
.newline=''
打开它。1An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect.可以给出一个可选的dialect参数,用于定义特定CSV方言的一组参数。It may be an instance of a subclass of the它可能是Dialect
class or one of the strings returned by thelist_dialects()
function.Dialect
类的子类的实例,也可能是list_dialects()
函数返回的字符串之一。The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.可以提供其他可选的fmtparms关键字参数来覆盖当前方言中的单个格式参数。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.从csv文件读取的每一行都作为字符串列表返回。No automatic data type conversion is performed unless the除非指定QUOTE_NONNUMERIC
format option is specified (in which case unquoted fields are transformed into floats).QUOTE_NONNUMERIC
格式选项(在这种情况下,未引用的字段转换为浮点),否则不会执行自动数据类型转换。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.返回一个writer对象,该对象负责将用户数据转换为给定类文件对象上的分隔字符串。csvfile can be any object with acsvfile可以是具有write()
method.write()
方法的任何对象。If csvfile is a file object, it should be opened with如果csvfile是文件对象,则应使用newline=''
1.newline=''
1打开它。An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect.可以给出一个可选的dialect参数,用于定义特定CSV方言的一组参数。It may be an instance of a subclass of the它可能是Dialect
class or one of the strings returned by thelist_dialects()
function.Dialect
类的子类的实例,也可能是list_dialects()
函数返回的字符串之一。The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.可以提供其他可选的fmtparms关键字参数来覆盖当前方言中的单个格式参数。For full details about dialects and formatting parameters, see the Dialects and Formatting Parameters section.有关方言和格式参数的完整详细信息,请参阅方言和格式参数部分。To make it as easy as possible to interface with modules which implement the DB API, the value为了尽可能容易地与实现DB API的模块进行接口,值None
is written as the empty string.None
被写为空字符串。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 a虽然这不是可逆转换,但它可以更轻松地将SQL空数据值转储到CSV文件,而无需预处理从cursor.fetch*
call.cursor.fetch*
调用返回的数据。All other non-string data are stringified with所有其他非字符串数据在写入之前用str()
before being written.str()
进行字符串化。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.把dialect和name联系起来。name must be a string.name必须是字符串。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.Dialect
来指定,也可以通过fmtparms关键字参数来指定,或者两者都可以,关键字参数覆盖方言参数。For full details about dialects and formatting parameters, see section Dialects and Formatting Parameters.有关方言和格式参数的完整详细信息,请参阅方言和格式参数一节。
-
csv.
unregister_dialect
(name)¶ Delete the dialect associated with name from the dialect registry.从方言注册表中删除与name关联的方言。An如果name不是注册的方言名称,则会引发Error
is raised if name is not a registered dialect name.Error
。
-
csv.
get_dialect
(name)¶ Return the dialect associated with name.返回与名称关联的name。An如果名称不是注册的方言名称,则会引发错误。Error
is raised if name is not a registered dialect name.This function returns an immutable此函数返回一个不可变的Dialect
.Dialect
。
-
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.如果给定了new_limit,则这将成为新极限。
The csv
module defines the following classes:csv
模块定义了以下类:
-
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 a创建一个像普通读取器一样运行的对象,但将每行中的信息映射到dict
whose keys are given by the optional fieldnames parameter.dict
,dict
的键由可选的fieldnames参数给定。The fieldnames parameter is a sequence.fieldnames参数是一个序列。If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames.如果省略fieldnames,则文件f第一行中的值将用作字段名。Regardless of how the fieldnames are determined, the 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如果一行的字段数大于字段名,则剩余的数据将放在一个列表中,并用restkey指定的字段名存储(默认为无)。None
).If a non-blank row has fewer fields than fieldnames, the missing values are filled-in with the value of restval (which defaults to如果非空行的字段数少于字段名,则缺少的值将用restval的值(默认为None
).None
)填充。All other optional or keyword arguments are passed to the underlying所有其他可选参数或关键字参数都传递给底层reader
instance.reader
实例。Changed in version 3.6:版本3.6中更改:Returned rows are now of type返回的行现在是OrderedDict
.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)
{'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 afieldnames参数是一个键sequence
of keys that identify the order in which values in the dictionary passed to thewriterow()
method are written to file f.sequence
,用于标识传递给writerow()
方法的字典中的值写入文件f的顺序。The optional restval parameter specifies the value to be written if the dictionary is missing a key in fieldnames.可选的restval参数指定如果字典在fieldnames中缺少键,则要写入的值。If the dictionary passed to the如果传递给writerow()
method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take.writerow()
方法的字典包含fieldnames中未找到的键,则可选的extrasaction参数指示要采取的操作。If it is set to如果将其设置为默认值'raise'
, the default value, aValueError
is raised.'raise'
,则会引发ValueError
。If it is set to如果设置为'ignore'
, extra values in the dictionary are ignored.'ignore'
,则忽略字典中的额外值。Any other optional or keyword arguments are passed to the underlying任何其他可选参数或关键字参数都会传递给底层writer
instance.writer
实例。Note that unlike the注意,与DictReader
class, the fieldnames parameter of theDictWriter
class is not optional.DictReader
类不同,DictWriter
类的fieldnames参数不是可选的。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
¶ TheDialect
class is a container class whose attributes contain information for how to handle doublequotes, whitespace, delimiters, etc.Dialect
类是一个容器类,其属性包含有关如何处理双引号、空格、分隔符等的信息。Due to the lack of a strict CSV specification, different applications produce subtly different CSV data.由于缺乏严格的CSV规范,不同的应用程序生成的CSV数据略有不同。Dialect
instances define howreader
andwriter
instances behave.Dialect
实例定义reader
和writer
实例的行为。All available所有可用的Dialect
names are returned bylist_dialects()
, and they can be registered with specificreader
andwriter
classes through their initializer (__init__
) functions like this:Dialect
名称都由list_dialogs()
返回,可以通过其初始值设定项(\uu init\uuuu)函数在特定的读写器类中注册,如下所示:import csv
with open('students.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, dialect='unix')
^^^^^^^^^^^^^^
-
class
csv.
excel
¶ Theexcel
class defines the usual properties of an Excel-generated CSV file.excel
类定义Excel生成的CSV文件的常规属性。It is registered with the dialect name它以方言名称'excel'
.'excel'
注册。
-
class
csv.
excel_tab
¶ Theexcel_tab
class defines the usual properties of an Excel-generated TAB-delimited file.excel_tab
类定义excel生成的制表符分隔文件的常规属性。It is registered with the dialect name它以方言名称'excel-tab'
.'excel-tab'
注册。
-
class
csv.
unix_dialect
¶ Theunix_dialect
class defines the usual properties of a CSV file generated on UNIX systems, i.e. using'\n'
as line terminator and quoting all fields.unix_dialect
类定义在unix系统上生成的CSV文件的常规属性,即使用'\n'
作为行终止符并引用所有字段。It is registered with the dialect name它以方言名称'unix'
.'unix'
注册。New in version 3.2.版本3.2中新增。
-
class
csv.
Sniffer
¶ TheSniffer
class is used to deduce the format of a CSV file.Sniffer
类用于推断CSV文件的格式。TheSniffer
class provides two methods:Sniffer
类提供了两种方法:-
sniff
(sample, delimiters=None)¶ Analyze the given sample and return a分析给定的sample并返回反映所发现参数的Dialect
subclass reflecting the parameters found.Dialect
子类。If the optional delimiters parameter is given, it is interpreted as a string containing possible valid delimiter characters.如果给定了可选的delimiters参数,则将其解释为包含可能的有效分隔符字符的字符串。
-
has_header
(sample)¶ Analyze the sample text (presumed to be in CSV format) and return分析示例文本(假定为CSV格式),如果第一行显示为一系列列标题,则返回True
if the first row appears to be a series of column headers.True
。Inspecting each column, one of two key criteria will be considered to estimate if the sample contains a header:检查每个列时,将考虑两个关键标准之一来估计样本是否包含标题:the second through n-th rows contain numeric values第二行到第n行包含数值the second through n-th rows contain strings where at least one value’s length differs from that of the putative header of that column.第二行到第n行包含字符串,其中至少有一个值的长度与该列的假定标头的长度不同。
Twenty rows after the first row are sampled; if more than half of columns + rows meet the criteria,对第一行后的20行进行采样;如果超过一半的列+行满足条件,则返回True
is returned.True
。
Note
This method is a rough heuristic and may produce both false positives and negatives.这种方法是一种粗略的启发式方法,可能会产生误报和否定。-
An example for Sniffer
use:Sniffer
使用示例:
with open('example.csv', newline='') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
# ... process CSV file contents here ...
The csv
module defines the following constants:csv
模块定义以下常数:
-
csv.
QUOTE_MINIMAL
¶ Instructs指示writer
objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.writer
对象仅引用包含特殊字符(如delimiter、quotechar或lineterminator中的任何字符)的字段。
-
csv.
QUOTE_NONNUMERIC
¶ Instructs指示writer
objects to quote all non-numeric fields.writer
对象引用所有非数字字段。Instructs the reader to convert all non-quoted fields to type float.指示读取器将所有非引号字段转换为float类型。
-
csv.
QUOTE_NONE
¶ Instructs指示writer
objects to never quote fields.writer
对象从不引用字段。When the current delimiter occurs in output data it is preceded by the current escapechar character.当当前delimiter出现在输出数据中时,它前面是当前escapechar字符。If escapechar is not set, the writer will raise如果未设置escapechar,则如果遇到任何需要转义的字符,写入程序将引发Error
if any characters that require escaping are encountered.Error
。Instructs指示reader
to perform no special processing of quote characters.reader
不执行引号字符的特殊处理。
The csv
module defines the following exception:csv
模块定义以下异常:
-
exception
csv.
Error
¶ Raised by any of the functions when an error is detected.检测到错误时由任何函数引发。
Dialects and Formatting Parameters方言和格式参数¶
To make it easier to specify the format of input and output records, specific formatting parameters are grouped together into dialects. 为了更容易指定输入和输出记录的格式,将特定的格式参数分组到方言中。A dialect is a subclass of the 方言是Dialect
class having a set of specific methods and a single validate()
method. Dialect
类的一个子类,具有一组特定方法和一个validate()
方法。When creating 当创建reader
or writer
objects, the programmer can specify a string or a subclass of the Dialect
class as the dialect parameter. reader
或writer
对象时,程序员可以指定一个字符串或Dialect
类的子类作为方言参数。In addition to, or instead of, the dialect parameter, the programmer can also specify individual formatting parameters, which have the same names as the attributes defined below for the 除了方言参数之外,或者代替方言参数,程序员还可以指定单个格式参数,这些参数与下面为Dialect
class.Dialect
类定义的属性具有相同的名称。
Dialects support the following attributes:方言支持以下属性:
-
Dialect.
delimiter
¶ A one-character string used to separate fields.用于分隔字段的单字符字符串。It defaults to它默认为','
.','
。
-
Dialect.
doublequote
¶ Controls how instances of quotechar appearing inside a field should themselves be quoted.控制如何引用字段内出现的quotechar实例。When如果为True
, the character is doubled.True
,则角色将加倍。When如果为False
, the escapechar is used as a prefix to the quotechar.False
,则escapechar用作quotechar的前缀。It defaults to默认为True
.True
。On output, if doublequote is在输出时,如果doublequote为False
and no escapechar is set,Error
is raised if a quotechar is found in a field.False
且未设置escapechar,则如果在字段中发现quotechar,则会引发Error
。
-
Dialect.
escapechar
¶ A one-character string used by the writer to escape the delimiter if quoting is set to如果引号设置为QUOTE_NONE
and the quotechar if doublequote isFalse
.QUOTE_NONE
,写入程序使用的一个字符串,用于转义分隔符;如果双引号为False
,则转义quotechar。On reading, the escapechar removes any special meaning from the following character.阅读时,escapechar会删除以下字符的任何特殊含义。It defaults to它默认为None
, which disables escaping.None
,这将禁用转义。
-
Dialect.
lineterminator
¶ The string used to terminate lines produced by the用于终止写入程序生成的行的字符串。writer
.It defaults to它默认为'\r\n'
.'\r\n'
。
-
Dialect.
quotechar
¶ A one-character string used to quote fields containing special characters, such as the delimiter or quotechar, or which contain new-line characters.一种单字符串,用于引用包含特殊字符(如delimiter或quotechar)的字段,或包含新行字符的字段。It defaults to它默认为'"'
.'"'
。
-
Dialect.
quoting
¶ Controls when quotes should be generated by the writer and recognised by the reader.控制何时应由作者生成报价并由读者识别。It can take on any of the它可以接受任何QUOTE_*
constants (see section Module Contents) and defaults toQUOTE_MINIMAL
.QUOTE_*
常量(请参阅模块内容一节),默认值为QUOTE_MINIMAL
。
Reader ObjectsReader
对象¶
Reader objects (读取器对象(DictReader
instances and objects returned by the reader()
function) have the following public methods:DictReader
实例和reader()
函数返回的对象)具有以下公共方法:
-
csvreader.
__next__
()¶ Return the next row of the reader’s iterable object as a list (if the object was returned from返回读取器iterable对象的下一行,作为列表(如果该对象是从reader()
) or a dict (if it is aDictReader
instance), parsed according to the currentDialect
.reader()
返回的)或dict(如果是DictReader
实例),根据当前Dialect
进行解析。Usually you should call this as通常,您应该将其称为next(reader)
.next(reader)
。
Reader objects have the following public attributes:读卡器对象具有以下公共属性:
-
csvreader.
dialect
¶ A read-only description of the dialect in use by the parser.解析器使用的方言的只读描述。
-
csvreader.
line_num
¶ The number of lines read from the source iterator.从源迭代器读取的行数。This is not the same as the number of records returned, as records can span multiple lines.这与返回的记录数不同,因为记录可以跨越多行。
DictReader objects have the following public attribute:DictReader对象具有以下公共属性:
-
csvreader.
fieldnames
¶ If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.如果在创建对象时未作为参数传递,则在首次访问或从文件中读取第一条记录时初始化该属性。
Writer
Objects对象¶
Writer
objects (DictWriter
instances and objects returned by the writer()
function) have the following public methods. Writer
对象(DictWriter
实例和writer()
函数返回的对象)具有以下公共方法。A row must be an iterable of strings or numbers for 对于Writer
objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str()
first) for DictWriter
objects. Writer
对象,row必须是字符串或数字的iterable,对于DictWriter
对象,行必须是将字段名映射到字符串或数字(首先通过str()
传递)的字典。Note that complex numbers are written out surrounded by parens. 请注意,复数是由paren包围写出的。This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).这可能会导致读取CSV文件的其他程序出现一些问题(假设它们完全支持复数)。
-
csvwriter.
writerow
(row)¶ Write the row parameter to the writer’s file object, formatted according to the current将row参数写入写入器的文件对象,并根据当前Dialect
.Dialect
进行格式化。Return the return value of the call to the write method of the underlying file object.返回对底层文件对象的write方法的调用的返回值。Changed in version 3.5:版本3.5中更改:Added support of arbitrary iterables.添加了对任意iterables的支持。
-
csvwriter.
writerows
(rows)¶ Write all elements in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.将rows中的所有元素(如上所述的row对象的一个iterable)写入编写器的文件对象,并根据当前方言进行格式化。
Writer objects have the following public attribute:Writer对象具有以下公共属性:
-
csvwriter.
dialect
¶ A read-only description of the dialect in use by the writer.对作者使用的方言的只读描述。
DictWriter objects have the following public method:DictWriter
对象具有以下公共方法:
-
DictWriter.
writeheader
()¶ Write a row with the field names (as specified in the constructor) to the writer’s file object, formatted according to the current dialect.将具有字段名(在构造函数中指定)的行写入编写器的文件对象,并根据当前方言进行格式化。Return the return value of the返回内部使用的csvwriter.writerow()
call used internally.csvwriter.writerow()
调用的返回值。New in version 3.2.版本3.2中新增。Changed in version 3.8:版本3.8中更改:writeheader()
now also returns the value returned by thecsvwriter.writerow()
method it uses internally.writeheader()
现在还返回它在内部使用的csvwriter.writerow()
方法返回的值。
Examples示例¶
The simplest example of reading a CSV file:读取CSV文件的最简单示例:
import csv
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
Reading a file with an alternate format:读取具有替代格式的文件:
import csv
with open('passwd', newline='') as f:
reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
for row in reader:
print(row)
The corresponding simplest possible writing example is:相应的最简单的书写示例是:
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(someiterable)
Since 由于open()
is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()
). open()
用于打开CSV文件进行读取,因此默认情况下,该文件将使用系统默认编码解码为unicode(请参阅locale.getpreferredencoding()
)。To decode a file using a different encoding, use the 要使用不同的编码对文件进行解码,请使用open的encoding
argument of open:encoding
参数:
import csv
with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
The same applies to writing in something other than the system default encoding: specify the encoding argument when opening the output file.这同样适用于以系统默认编码以外的方式写入:在打开输出文件时指定编码参数。
Registering a new dialect:注册新方言:
import csv
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('passwd', newline='') as f:
reader = csv.reader(f, 'unixpwd')
A slightly more advanced use of the reader — catching and reporting errors:读者捕捉和报告错误的更高级使用:
import csv, sys
filename = 'some.csv'
with open(filename, newline='') as f:
reader = csv.reader(f)
try:
for row in reader:
print(row)
except csv.Error as e:
sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
And while the module doesn’t directly support parsing strings, it can easily be done:虽然模块不直接支持解析字符串,但很容易做到:
import csv
for row in csv.reader(['one,two,three']):
print(row)
Footnotes
- 1(1,2)
If如果未指定newline=''
is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use\r\n
linendings on write an extra\r
will be added.newline=''
,嵌入在带引号字段中的换行符将无法正确解释,并且在写入时使用\r\n
换行符的平台上,将添加额外的\r
。It should always be safe to specify指定newline=''
, since the csv module does its own (universal) newline handling.newline=''
应该总是安全的,因为csv模块有自己的(通用)换行符处理。