“Python/docs/3.9/library/csv”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/csv
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:csv — CSV 文件读写 — Python 文档}}
 
<div id="module-csv" class="section">
 
<div id="module-csv" class="section">
  
 
<span id="csv-csv-file-reading-and-writing"></span>
 
<span id="csv-csv-file-reading-and-writing"></span>
= [[#module-csv|<code>csv</code>]] --- CSV File Reading and Writing =
+
= csv CSV 文件读写 =
  
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/csv.py Lib/csv.py]
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/csv.py`</span>]]
  
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
 
<span id="index-1" class="target"></span>[https://tools.ietf.org/html/rfc4180.html '''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 [[#module-csv|<code>csv</code>]] module implements classes to read and write tabular data in CSV
+
-----
format. It allows programmers to say, &quot;write this data in the format preferred
 
by Excel,&quot; or &quot;read data from this file which was generated by Excel,&quot; 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 [[#module-csv|<code>csv</code>]] module's [[#csv.reader|<code>reader</code>]] and [[#csv.writer|<code>writer</code>]] objects read and
+
所谓的 CSV(逗号分隔值)格式是电子表格和数据库最常见的导入和导出格式。 在 <span id="index-1" class="target"></span>[https://tools.ietf.org/html/rfc4180.html RFC 4180] 中尝试以标准化方式描述格式之前,CSV 格式已使用多年。 缺乏明确定义的标准意味着不同应用程序产生和使用的数据往往存在细微差别。 这些差异会使处理来自多个来源的 CSV 文件变得烦人。 尽管如此,虽然分隔符和引用字符各不相同,但整体格式足够相似,以至于可以编写一个可以有效操作此类数据的模块,从而对程序员隐藏读取和写入数据的细节。
write sequences. Programmers can also read and write data in dictionary form
+
 
using the [[#csv.DictReader|<code>DictReader</code>]] and [[#csv.DictWriter|<code>DictWriter</code>]] classes.
+
[[#module-csv|csv]] 模块实现类以读取和写入 CSV 格式的表格数据。 它允许程序员说“以 Excel 首选的格式写入此数据”或“从 Excel 生成的此文件中读取数据”,而无需知道 Excel 使用的 CSV 格式的确切细节。 程序员还可以描述其他应用程序可以理解的 CSV 格式或定义自己的专用 CSV 格式。
 +
 
 +
[[#module-csv|csv]] 模块的 [[#csv.reader|reader]] [[#csv.writer|writer]] 对象读取和写入序列。 程序员还可以使用 [[#csv.DictReader|DictReader]] [[#csv.DictWriter|DictWriter]] 类以字典形式读取和写入数据。
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-2" class="target"></span>[https://www.python.org/dev/peps/pep-0305 '''PEP 305'''] - CSV File API
+
; <span id="index-2" class="target"></span>[https://www.python.org/dev/peps/pep-0305 PEP 305] - CSV 文件 API
: The Python Enhancement Proposal which proposed this addition to Python.
+
: 提议对 Python 进行此添加的 Python 增强提案。
  
  
第40行: 第28行:
  
 
<span id="csv-contents"></span>
 
<span id="csv-contents"></span>
== Module Contents ==
+
== 模块内容 ==
  
The [[#module-csv|<code>csv</code>]] module defines the following functions:
+
[[#module-csv|csv]] 模块定义了以下函数:
  
 
<span id="index-3" class="target"></span>
 
<span id="index-3" class="target"></span>
 
<dl>
 
<dl>
<dt><code>csv.</code><code>reader</code><span class="sig-paren">(</span>''<span class="n">csvfile</span>'', ''<span class="n">dialect</span><span class="o">=</span><span class="default_value">'excel'</span>'', ''<span class="o">**</span><span class="n">fmtparams</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">reader</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">csvfile</span></span>'', ''<span class="n"><span class="pre">dialect</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'excel'</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">fmtparams</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a reader object which will iterate over lines in the given ''csvfile''.
+
<dd><p>返回一个读取器对象,该对象将遍历给定的 ''csvfile'' 中的行。 ''csvfile'' 可以是任何支持 [[../../glossary#term-iterator|iterator]] 协议并在每次调用其 <code>__next__()</code> 方法时返回一个字符串的对象——[[../../glossary#term-file-object|file objects]] list objects两者都合适。 如果 ''csvfile'' 是文件对象,则应使用 <code>newline=''</code> 打开。 [[#id5|1]] 可以给出可选的 ''dialect'' 参数,用于定义特定于特定 CSV 方言的一组参数。 它可能是 [[#csv.Dialect|Dialect]] 类的子类的实例,也可能是 [[#csv.list_dialects|list_dialects()]] 函数返回的字符串之一。 可以给出其他可选的 ''fmtparams'' 关键字参数来覆盖当前方言中的各个格式参数。 有关方言和格式参数的完整详细信息,请参阅 [[#csv-fmt-params|方言和格式参数]] 部分。</p>
''csvfile'' can be any object which supports the [[../../glossary#term-iterator|<span class="xref std std-term">iterator</span>]] protocol and returns a
+
<p>csv 文件读取的每一行都作为字符串列表返回。 除非指定了 <code>QUOTE_NONNUMERIC</code> 格式选项(在这种情况下未加引号的字段被转换为浮点数),否则不会执行自动数据类型转换。</p>
string each time its <code>__next__()</code> method is called --- [[../../glossary#term-file-object|<span class="xref std std-term">file objects</span>]] and list objects are both suitable. If ''csvfile'' is a file object,
+
<p>一个简短的用法示例:</p>
it should be opened with <code>newline=''</code>. [[#id3|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
 
the [[#csv.Dialect|<code>Dialect</code>]] class or one of the strings returned by the
 
[[#csv.list_dialects|<code>list_dialects()</code>]] 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 [[#csv-fmt-params|<span class="std std-ref">Dialects and Formatting Parameters</span>]].</p>
 
<p>Each row read from the csv file is returned as a list of strings. No
 
automatic data type conversion is performed unless the <code>QUOTE_NONNUMERIC</code> format
 
option is specified (in which case unquoted fields are transformed into floats).</p>
 
<p>A short usage example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import csv
+
<syntaxhighlight lang="python3">>>> import csv
&gt;&gt;&gt; with open('eggs.csv', newline='') as csvfile:
+
>>> with open('eggs.csv', newline='') as csvfile:
 
...    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
 
...    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
 
...    for row in spamreader:
 
...    for row in spamreader:
 
...        print(', '.join(row))
 
...        print(', '.join(row))
 
Spam, Spam, Spam, Spam, Spam, Baked Beans
 
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam</pre>
+
Spam, Lovely Spam, Wonderful Spam</syntaxhighlight>
  
 
</div>
 
</div>
第79行: 第55行:
  
 
<dl>
 
<dl>
<dt><code>csv.</code><code>writer</code><span class="sig-paren">(</span>''<span class="n">csvfile</span>'', ''<span class="n">dialect</span><span class="o">=</span><span class="default_value">'excel'</span>'', ''<span class="o">**</span><span class="n">fmtparams</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">writer</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">csvfile</span></span>'', ''<span class="n"><span class="pre">dialect</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'excel'</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">fmtparams</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a writer object responsible for converting the user's data into delimited
+
<dd><p>返回一个 writer 对象,负责将用户的数据转换为给定的类文件对象上的分隔字符串。 ''csvfile'' 可以是具有 <code>write()</code> 方法的任何对象。 如果 ''csvfile'' 是文件对象,则应使用 <code>newline=''</code> [[#id5|1]] 打开。 可以给出可选的 ''dialect'' 参数,用于定义特定于特定 CSV 方言的一组参数。 它可能是 [[#csv.Dialect|Dialect]] 类的子类的实例,也可能是 [[#csv.list_dialects|list_dialects()]] 函数返回的字符串之一。 可以给出其他可选的 ''fmtparams'' 关键字参数来覆盖当前方言中的各个格式参数。 有关方言和格式参数的完整详细信息,请参阅 [[#csv-fmt-params|方言和格式参数]] 部分。 为了尽可能容易地与实现 DB API 的模块交互,值 [[../constants#None|None]] 被写为空字符串。 虽然这不是可逆转换,但它可以更轻松地将 SQL NULL 数据值转储到 CSV 文件,而无需预处理从 <code>cursor.fetch*</code> 调用返回的数据。 所有其他非字符串数据在写入之前都使用 [[../stdtypes#str|str()]] 进行字符串化。</p>
strings on the given file-like object. ''csvfile'' can be any object with a
+
<p>一个简短的用法示例:</p>
<code>write()</code> method. If ''csvfile'' is a file object, it should be opened with
 
<code>newline=''</code> [[#id3|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 the
 
[[#csv.Dialect|<code>Dialect</code>]] class or one of the strings returned by the
 
[[#csv.list_dialects|<code>list_dialects()</code>]] 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 [[#csv-fmt-params|<span class="std std-ref">Dialects and Formatting Parameters</span>]]. To make it
 
as easy as possible to interface with modules which implement the DB API, the
 
value [[../constants#None|<code>None</code>]] is 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 a <code>cursor.fetch*</code> call.
 
All other non-string data are stringified with [[../stdtypes#str|<code>str()</code>]] before being written.</p>
 
<p>A short usage example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv
+
<syntaxhighlight lang="python3">import csv
 
with open('eggs.csv', 'w', newline='') as csvfile:
 
with open('eggs.csv', 'w', newline='') as csvfile:
 
     spamwriter = csv.writer(csvfile, delimiter=' ',
 
     spamwriter = csv.writer(csvfile, delimiter=' ',
 
                             quotechar='|', quoting=csv.QUOTE_MINIMAL)
 
                             quotechar='|', quoting=csv.QUOTE_MINIMAL)
 
     spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
 
     spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
     spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])</pre>
+
     spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])</syntaxhighlight>
  
 
</div>
 
</div>
第112行: 第73行:
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>csv.</code><code>register_dialect</code><span class="sig-paren">(</span>''name''<span class="optional">[</span>, ''dialect''<span class="optional">[</span>, ''**fmtparams''<span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">register_dialect</span></span><span class="sig-paren">(</span>''<span class="pre">name</span>''<span class="optional">[</span>, ''<span class="pre">dialect</span>''<span class="optional">[</span>, ''<span class="pre">**fmtparams</span>''<span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span>
: Associate ''dialect'' with ''name''. ''name'' must be a string. The dialect can be specified either by passing a sub-class of [[#csv.Dialect|<code>Dialect</code>]], 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 [[#csv-fmt-params|<span class="std std-ref">Dialects and Formatting Parameters</span>]].
+
: ''方言'' ''名称'' 相关联。 ''name'' 必须是字符串。 可以通过传递 [[#csv.Dialect|Dialect]] 的子类或通过 ''fmtparams'' 关键字参数或两者来指定方言,并使用关键字参数覆盖方言的参数。 有关方言和格式参数的完整详细信息,请参阅 [[#csv-fmt-params|方言和格式参数]] 部分。
  
; <code>csv.</code><code>unregister_dialect</code><span class="sig-paren">(</span>''<span class="n">name</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">unregister_dialect</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span>''<span class="sig-paren">)</span>
: Delete the dialect associated with ''name'' from the dialect registry. An [[#csv.Error|<code>Error</code>]] is raised if ''name'' is not a registered dialect name.
+
: 从方言注册表中删除与 ''name'' 关联的方言。 如果 ''name'' 不是已注册的方言名称,则会引发 [[#csv.Error|Error]]
  
; <code>csv.</code><code>get_dialect</code><span class="sig-paren">(</span>''<span class="n">name</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">get_dialect</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span>''<span class="sig-paren">)</span>
: Return the dialect associated with ''name''. An [[#csv.Error|<code>Error</code>]] is raised if ''name'' is not a registered dialect name. This function returns an immutable [[#csv.Dialect|<code>Dialect</code>]].
+
: 返回与 ''name'' 关联的方言。 如果 ''name'' 不是已注册的方言名称,则会引发 [[#csv.Error|Error]]。 此函数返回一个不可变的 [[#csv.Dialect|方言]]
  
; <code>csv.</code><code>list_dialects</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">list_dialects</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return the names of all registered dialects.
+
: 返回所有已注册方言的名称。
  
; <code>csv.</code><code>field_size_limit</code><span class="sig-paren">(</span><span class="optional">[</span>''new_limit''<span class="optional">]</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">field_size_limit</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">new_limit</span>''<span class="optional">]</span><span class="sig-paren">)</span>
: Returns the current maximum field size allowed by the parser. If ''new_limit'' is given, this becomes the new limit.
+
: 返回解析器允许的当前最大字段大小。 如果给出 ''new_limit'',这将成为新的限制。
  
The [[#module-csv|<code>csv</code>]] module defines the following classes:
+
[[#module-csv|csv]] 模块定义了以下类:
  
 
<dl>
 
<dl>
<dt>''class'' <code>csv.</code><code>DictReader</code><span class="sig-paren">(</span>''<span class="n">f</span>'', ''<span class="n">fieldnames</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">restkey</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">restval</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">dialect</span><span class="o">=</span><span class="default_value">'excel'</span>'', ''<span class="o">*</span><span class="n">args</span>'', ''<span class="o">**</span><span class="n">kwds</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">DictReader</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">f</span></span>'', ''<span class="n"><span class="pre">fieldnames</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">restkey</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">restval</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">dialect</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'excel'</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Create an object that operates like a regular reader but maps the
+
<dd><p>创建一个对象,其操作类似于常规阅读器,但将每一行中的信息映射到 [[../stdtypes#dict|dict]],其键由可选的 ''fieldnames'' 参数给出。</p>
information in each row to a [[../stdtypes#dict|<code>dict</code>]] whose keys are given by the
+
<p>''fieldnames'' 参数是一个 [[../../glossary#term-sequence|序列]] 。 如果省略 ''fieldnames'',则将使用文件 ''f'' 第一行中的值作为字段名。 不管如何确定字段名,字典都会保留它们的原始顺序。</p>
optional ''fieldnames'' parameter.</p>
+
<p>如果一行的字段数多于字段名,则剩余的数据将放入一个列表中,并以 ''restkey''(默认为 <code>None</code>)指定的字段名存储。 如果非空行的字段数少于字段名,则使用 ''restval'' 值(默认为 <code>None</code>)填充缺失值。</p>
<p>The ''fieldnames'' parameter is a [[../../glossary#term-sequence|<span class="xref std std-term">sequence</span>]]. If ''fieldnames'' is
+
<p>所有其他可选或关键字参数都传递给底层 [[#csv.reader|reader]] 实例。</p>
omitted, the values in the first row of file ''f'' will be used as the
 
fieldnames. Regardless of how the fieldnames are determined, the
 
dictionary preserves their original ordering.</p>
 
<p>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 <code>None</code>). If a non-blank row has fewer fields than fieldnames, the
 
missing values are filled-in with the value of ''restval'' (which defaults
 
to <code>None</code>).</p>
 
<p>All other optional or keyword arguments are passed to the underlying
 
[[#csv.reader|<code>reader</code>]] instance.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.6 版更改: </span>Returned rows are now of type <code>OrderedDict</code>.</p>
+
<p><span class="versionmodified changed">在 3.6 版更改:</span>返回的行现在是 <code>OrderedDict</code> 类型。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.8 版更改: </span>Returned rows are now of type [[../stdtypes#dict|<code>dict</code>]].</p>
+
<p><span class="versionmodified changed">在 3.8 版更改:</span>返回的行现在是 [[../stdtypes#dict|dict]] 类型。</p>
  
 
</div>
 
</div>
<p>A short usage example:</p>
+
<p>一个简短的用法示例:</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import csv
+
<syntaxhighlight lang="python3">>>> import csv
&gt;&gt;&gt; with open('names.csv', newline='') as csvfile:
+
>>> with open('names.csv', newline='') as csvfile:
 
...    reader = csv.DictReader(csvfile)
 
...    reader = csv.DictReader(csvfile)
 
...    for row in reader:
 
...    for row in reader:
第169行: 第120行:
 
John Cleese
 
John Cleese
  
&gt;&gt;&gt; print(row)
+
>>> print(row)
{'first_name': 'John', 'last_name': 'Cleese'}</pre>
+
{'first_name': 'John', 'last_name': 'Cleese'}</syntaxhighlight>
  
 
</div>
 
</div>
第177行: 第128行:
  
 
<dl>
 
<dl>
<dt>''class'' <code>csv.</code><code>DictWriter</code><span class="sig-paren">(</span>''<span class="n">f</span>'', ''<span class="n">fieldnames</span>'', ''<span class="n">restval</span><span class="o">=</span><span class="default_value">''</span>'', ''<span class="n">extrasaction</span><span class="o">=</span><span class="default_value">'raise'</span>'', ''<span class="n">dialect</span><span class="o">=</span><span class="default_value">'excel'</span>'', ''<span class="o">*</span><span class="n">args</span>'', ''<span class="o">**</span><span class="n">kwds</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">DictWriter</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">f</span></span>'', ''<span class="n"><span class="pre">fieldnames</span></span>'', ''<span class="n"><span class="pre">restval</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span>'', ''<span class="n"><span class="pre">extrasaction</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'raise'</span></span>'', ''<span class="n"><span class="pre">dialect</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'excel'</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Create an object which operates like a regular writer but maps dictionaries
+
<dd><p>创建一个对象,其操作类似于常规编写器,但将字典映射到输出行。 ''fieldnames'' 参数是键的 [[../collections.abc#module-collections|序列]],用于标识传递给 <code>writerow()</code> 方法的字典中的值写入文件 ''f'' 的顺序]。 可选的 ''restval'' 参数指定在字典缺少 ''fieldnames'' 中的键时要写入的值。 如果传递给 <code>writerow()</code> 方法的字典包含在 ''fieldnames'' 中找不到的键,则可选的 ''extrasaction'' 参数指示要采取的操作。 如果设置为 <code>'raise'</code>(默认值),则会引发 [[../exceptions#ValueError|ValueError]]。 如果设置为 <code>'ignore'</code>,则字典中的额外值将被忽略。 任何其他可选或关键字参数都传递给底层 [[#csv.writer|writer]] 实例。</p>
onto output rows. The ''fieldnames'' parameter is a [[../collections.abc#module-collections|<code>sequence</code>]] of keys that identify the order in which values in the
+
<p>请注意,与 [[#csv.DictReader|DictReader]] 类不同,[[#csv.DictWriter|DictWriter]] 类的 ''fieldnames'' 参数不是可选的。</p>
dictionary passed to the <code>writerow()</code> method are written to file
+
<p>一个简短的用法示例:</p>
''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 the <code>writerow()</code> method contains a key not found in
 
''fieldnames'', the optional ''extrasaction'' parameter indicates what action to
 
take.
 
If it is set to <code>'raise'</code>, the default value, a [[../exceptions#ValueError|<code>ValueError</code>]]
 
is raised.
 
If it is set to <code>'ignore'</code>, extra values in the dictionary are ignored.
 
Any other optional or keyword arguments are passed to the underlying
 
[[#csv.writer|<code>writer</code>]] instance.</p>
 
<p>Note that unlike the [[#csv.DictReader|<code>DictReader</code>]] class, the ''fieldnames'' parameter
 
of the [[#csv.DictWriter|<code>DictWriter</code>]] class is not optional.</p>
 
<p>A short usage example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv
+
<syntaxhighlight lang="python3">import csv
  
 
with open('names.csv', 'w', newline='') as csvfile:
 
with open('names.csv', 'w', newline='') as csvfile:
第207行: 第145行:
 
     writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
 
     writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
 
     writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
 
     writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
     writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})</pre>
+
     writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})</syntaxhighlight>
  
 
</div>
 
</div>
第213行: 第151行:
 
</div></dd></dl>
 
</div></dd></dl>
  
; ''class'' <code>csv.</code><code>Dialect</code>
+
<dl>
: The [[#csv.Dialect|<code>Dialect</code>]] class is a container class relied on primarily for its attributes, which are used to define the parameters for a specific [[#csv.reader|<code>reader</code>]] or [[#csv.writer|<code>writer</code>]] instance.
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">Dialect</span></span></dt>
 +
<dd><p>[[#csv.Dialect|Dialect]] 类是一个容器类,其属性包含有关如何处理双引号、空格、分隔符等的信息。 由于缺乏严格的 CSV 规范,不同的应用程序生成的 CSV 数据略有不同。 [[#csv.Dialect|Dialect]] 实例定义了 [[#csv.reader|reader]] 和 [[#csv.writer|writer]] 实例的行为方式。</p>
 +
<p>所有可用的 [[#csv.Dialect|Dialect]] 名称都由 [[#csv.list_dialects|list_dialects()]] 返回,它们可以通过它们的初始化程序注册到特定的 [[#csv.reader|reader]] [[#csv.writer|writer]] 类( <code>__init__</code>) 功能如下:</p>
 +
<div class="highlight-python3 notranslate">
 +
 
 +
<div class="highlight">
 +
 
 +
<syntaxhighlight lang="python3">import csv
 +
 
 +
with open('students.csv', 'w', newline='') as csvfile:
 +
    writer = csv.writer(csvfile, dialect='unix')
 +
                                ^^^^^^^^^^^^^^</syntaxhighlight>
 +
 
 +
</div>
 +
 
 +
</div></dd></dl>
  
; ''class'' <code>csv.</code><code>excel</code>
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">excel</span></span>
: The [[#csv.excel|<code>excel</code>]] class defines the usual properties of an Excel-generated CSV file. It is registered with the dialect name <code>'excel'</code>.
+
: [[#csv.excel|excel]] 类定义了 Excel 生成的 CSV 文件的常用属性。 它以方言名称 <code>'excel'</code> 注册。
  
; ''class'' <code>csv.</code><code>excel_tab</code>
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">excel_tab</span></span>
: The [[#csv.excel_tab|<code>excel_tab</code>]] class defines the usual properties of an Excel-generated TAB-delimited file. It is registered with the dialect name <code>'excel-tab'</code>.
+
: [[#csv.excel_tab|excel_tab]] 类定义 Excel 生成的制表符分隔文件的常用属性。 它以方言名称 <code>'excel-tab'</code> 注册。
  
 
<dl>
 
<dl>
<dt>''class'' <code>csv.</code><code>unix_dialect</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">unix_dialect</span></span></dt>
<dd><p>The [[#csv.unix_dialect|<code>unix_dialect</code>]] class defines the usual properties of a CSV file
+
<dd><p>[[#csv.unix_dialect|unix_dialect]] 类定义了在 UNIX 系统上生成的 CSV 文件的常用属性,即 使用 <code>'\n'</code> 作为行终止符并引用所有字段。 它以方言名称 <code>'unix'</code> 注册。</p>
generated on UNIX systems, i.e. using <code>'\n'</code> as line terminator and quoting
 
all fields. It is registered with the dialect name <code>'unix'</code>.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.2 新版功能.</span></p>
+
<p><span class="versionmodified added">3.2 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt>''class'' <code>csv.</code><code>Sniffer</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">Sniffer</span></span></dt>
<dd><p>The [[#csv.Sniffer|<code>Sniffer</code>]] class is used to deduce the format of a CSV file.</p>
+
<dd><p>[[#csv.Sniffer|Sniffer]] 类用于推断 CSV 文件的格式。</p>
<p>The [[#csv.Sniffer|<code>Sniffer</code>]] class provides two methods:</p>
+
<p>[[#csv.Sniffer|Sniffer]] 类提供了两种方法:</p>
 
<dl>
 
<dl>
<dt><code>sniff</code><span class="sig-paren">(</span>''<span class="n">sample</span>'', ''<span class="n">delimiters</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">sniff</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">sample</span></span>'', ''<span class="n"><span class="pre">delimiters</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Analyze the given ''sample'' and return a [[#csv.Dialect|<code>Dialect</code>]] subclass
+
<dd><p>分析给定的 ''sample'' 并返回反映找到的参数的 [[#csv.Dialect|Dialect]] 子类。 如果给出了可选的 ''delimiters'' 参数,则它被解释为包含可能的有效分隔符的字符串。</p></dd></dl>
reflecting the parameters found. If the optional ''delimiters'' parameter
 
is given, it is interpreted as a string containing possible valid
 
delimiter characters.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>has_header</code><span class="sig-paren">(</span>''<span class="n">sample</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">has_header</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">sample</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Analyze the sample text (presumed to be in CSV format) and return
+
<dd><p>分析示例文本(假定为 CSV 格式),如果第一行显示为一系列列标题,则返回 [[../constants#True|True]]</p></dd></dl>
[[../constants#True|<code>True</code>]] if the first row appears to be a series of column headers.</p></dd></dl>
 
 
</dd></dl>
 
</dd></dl>
  
An example for [[#csv.Sniffer|<code>Sniffer</code>]] use:
+
[[#csv.Sniffer|Sniffer]] 使用示例:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第256行: 第203行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>with open('example.csv', newline='') as csvfile:
+
<syntaxhighlight lang="python3">with open('example.csv', newline='') as csvfile:
 
     dialect = csv.Sniffer().sniff(csvfile.read(1024))
 
     dialect = csv.Sniffer().sniff(csvfile.read(1024))
 
     csvfile.seek(0)
 
     csvfile.seek(0)
 
     reader = csv.reader(csvfile, dialect)
 
     reader = csv.reader(csvfile, dialect)
     # ... process CSV file contents here ...</pre>
+
     # ... process CSV file contents here ...</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[#module-csv|<code>csv</code>]] module defines the following constants:
+
[[#module-csv|csv]] 模块定义了以下常量:
  
; <code>csv.</code><code>QUOTE_ALL</code>
+
; <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_ALL</span></span>
: Instructs [[#csv.writer|<code>writer</code>]] objects to quote all fields.
+
: 指示 [[#csv.writer|writer]] 对象引用所有字段。
  
; <code>csv.</code><code>QUOTE_MINIMAL</code>
+
; <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_MINIMAL</span></span>
: Instructs [[#csv.writer|<code>writer</code>]] objects to only quote those fields which contain special characters such as ''delimiter'', ''quotechar'' or any of the characters in ''lineterminator''.
+
: 指示 [[#csv.writer|writer]] 对象仅引用包含特殊字符的字段,例如 ''delimiter''''quotechar'' ''lineterminator'' 中的任何字符。
  
 
<dl>
 
<dl>
<dt><code>csv.</code><code>QUOTE_NONNUMERIC</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_NONNUMERIC</span></span></dt>
<dd><p>Instructs [[#csv.writer|<code>writer</code>]] objects to quote all non-numeric fields.</p>
+
<dd><p>指示 [[#csv.writer|writer]] 对象引用所有非数字字段。</p>
<p>Instructs the reader to convert all non-quoted fields to type ''float''.</p></dd></dl>
+
<p>指示读者将所有未引用的字段转换为类型 ''float''</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>csv.</code><code>QUOTE_NONE</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">QUOTE_NONE</span></span></dt>
<dd><p>Instructs [[#csv.writer|<code>writer</code>]] objects to never quote fields. When the current
+
<dd><p>指示 [[#csv.writer|writer]] 对象从不引用字段。 当当前的 ''分隔符'' 出现在输出数据中时,它前面是当前的 ''escapechar'' 字符。 如果未设置 ''escapechar'',则在遇到任何需要转义的字符时,编写器将引发 [[#csv.Error|Error]]</p>
''delimiter'' occurs in output data it is preceded by the current ''escapechar''
+
<p>指示 [[#csv.reader|reader]] 不对引号字符进行特殊处理。</p></dd></dl>
character. If ''escapechar'' is not set, the writer will raise [[#csv.Error|<code>Error</code>]] if
 
any characters that require escaping are encountered.</p>
 
<p>Instructs [[#csv.reader|<code>reader</code>]] to perform no special processing of quote characters.</p></dd></dl>
 
  
The [[#module-csv|<code>csv</code>]] module defines the following exception:
+
[[#module-csv|csv]] 模块定义了以下异常:
  
; ''exception'' <code>csv.</code><code>Error</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">csv.</span></span><span class="sig-name descname"><span class="pre">Error</span></span>
: Raised by any of the functions when an error is detected.
+
: 检测到错误时由任何函数引发。
  
  
第296行: 第240行:
  
 
<span id="csv-fmt-params"></span>
 
<span id="csv-fmt-params"></span>
== Dialects and Formatting Parameters ==
+
== 方言和格式参数 ==
  
To make it easier to specify the format of input and output records, specific
+
为了更容易地指定输入和输出记录的格式,特定的格式参数被组合到方言中。 方言是 [[#csv.Dialect|Dialect]] 类的子类,具有一组特定方法和一个 <code>validate()</code> 方法。 在创建 [[#csv.reader|reader]] [[#csv.writer|writer]] 对象时,程序员可以指定一个字符串或 [[#csv.Dialect|Dialect]] 类的子类作为方言参数。 除了或代替 ''dialect'' 参数,程序员还可以指定单独的格式化参数,这些参数与下面为 [[#csv.Dialect|Dialect]] 类定义的属性具有相同的名称。
formatting parameters are grouped together into dialects. A dialect is a
 
subclass of the [[#csv.Dialect|<code>Dialect</code>]] class having a set of specific methods and a
 
single <code>validate()</code> method. When creating [[#csv.reader|<code>reader</code>]] or
 
[[#csv.writer|<code>writer</code>]] objects, the programmer can specify a string or a subclass of
 
the [[#csv.Dialect|<code>Dialect</code>]] class as the dialect parameter. 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 [[#csv.Dialect|<code>Dialect</code>]] class.
 
  
Dialects support the following attributes:
+
方言支持以下属性:
  
; <code>Dialect.</code><code>delimiter</code>
+
; <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">delimiter</span></span>
: A one-character string used to separate fields. It defaults to <code>','</code>.
+
: 用于分隔字段的单字符字符串。 默认为 <code>','</code>
  
 
<dl>
 
<dl>
<dt><code>Dialect.</code><code>doublequote</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">doublequote</span></span></dt>
<dd><p>Controls how instances of ''quotechar'' appearing inside a field should
+
<dd><p>控制如何引用字段内出现的 ''quotechar'' 实例本身。 当[[../constants#True|True]]时,字符加倍。 当 [[../constants#False|False]] 时,''escapechar'' 用作 ''quotechar'' 的前缀。 默认为 [[../constants#True|True]]</p>
themselves be quoted. When [[../constants#True|<code>True</code>]], the character is doubled. When
+
<p>在输出时,如果 ''doublequote'' [[../constants#False|False]] 并且没有设置 ''escapechar'',如果 ''quotechar'' 是 [[#csv.Error|Error]]在一个领域找到。</p></dd></dl>
[[../constants#False|<code>False</code>]], the ''escapechar'' is used as a prefix to the ''quotechar''. It
 
defaults to [[../constants#True|<code>True</code>]].</p>
 
<p>On output, if ''doublequote'' is [[../constants#False|<code>False</code>]] and no ''escapechar'' is set,
 
[[#csv.Error|<code>Error</code>]] is raised if a ''quotechar'' is found in a field.</p></dd></dl>
 
  
; <code>Dialect.</code><code>escapechar</code>
+
; <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">escapechar</span></span>
: A one-character string used by the writer to escape the ''delimiter'' if ''quoting'' is set to [[#csv.QUOTE_NONE|<code>QUOTE_NONE</code>]] and the ''quotechar'' if ''doublequote'' is [[../constants#False|<code>False</code>]]. On reading, the ''escapechar'' removes any special meaning from the following character. It defaults to [[../constants#None|<code>None</code>]], which disables escaping.
+
: 如果 ''quoting'' 设置为 [[#csv.QUOTE_NONE|QUOTE_NONE]] ''quotechar'' 如果 ''双引号'' [[../constants#False|]]。 读取时,''escapechar'' 会删除以下字符的任何特殊含义。 它默认为 [[../constants#None|None]],禁用转义。
  
 
<dl>
 
<dl>
<dt><code>Dialect.</code><code>lineterminator</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">lineterminator</span></span></dt>
<dd><p>The string used to terminate lines produced by the [[#csv.writer|<code>writer</code>]]. It defaults
+
<dd><p>用于终止由 [[#csv.writer|writer]] 生成的行的字符串。 默认为 <code>'\r\n'</code></p>
to <code>'\r\n'</code>.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>The [[#csv.reader|<code>reader</code>]] is hard-coded to recognise either <code>'\r'</code> or <code>'\n'</code> as
+
<p>[[#csv.reader|reader]] 被硬编码以将 <code>'\r'</code> <code>'\n'</code> 识别为行尾,并忽略 ''lineterminator''。 这种行为将来可能会改变。</p>
end-of-line, and ignores ''lineterminator''. This behavior may change in the
 
future.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>Dialect.</code><code>quotechar</code>
+
; <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">quotechar</span></span>
: A one-character string used to quote fields containing special characters, such as the ''delimiter'' or ''quotechar'', or which contain new-line characters. It defaults to <code>'&quot;'</code>.
+
: 用于引用包含特殊字符(例如 ''delimiter'' ''quotechar'')或包含换行符的字段的单字符字符串。 默认为 <code>'&quot;'</code>
  
; <code>Dialect.</code><code>quoting</code>
+
; <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">quoting</span></span>
: Controls when quotes should be generated by the writer and recognised by the reader. It can take on any of the <code>QUOTE_*</code> constants (see section [[#csv-contents|<span class="std std-ref">Module Contents</span>]]) and defaults to [[#csv.QUOTE_MINIMAL|<code>QUOTE_MINIMAL</code>]].
+
: 控制何时应由作者生成引号并由读者识别。 它可以采用任何 <code>QUOTE_*</code> 常量(请参阅 [[#csv-contents|模块内容]] 部分)并默认为 [[#csv.QUOTE_MINIMAL|QUOTE_MINIMAL]]
  
; <code>Dialect.</code><code>skipinitialspace</code>
+
; <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">skipinitialspace</span></span>
: When [[../constants#True|<code>True</code>]], whitespace immediately following the ''delimiter'' is ignored. The default is [[../constants#False|<code>False</code>]].
+
: [[../constants#True|True]] 时,紧跟在 ''定界符'' 之后的空格将被忽略。 默认值为 [[../constants#False|False]]
  
; <code>Dialect.</code><code>strict</code>
+
; <span class="sig-prename descclassname"><span class="pre">Dialect.</span></span><span class="sig-name descname"><span class="pre">strict</span></span>
: When <code>True</code>, raise exception [[#csv.Error|<code>Error</code>]] on bad CSV input. The default is <code>False</code>.
+
: <code>True</code> 时,在错误的 CSV 输入上引发异常 [[#csv.Error|Error]]。 默认值为 <code>False</code>
  
  
第354行: 第283行:
 
<div id="reader-objects" class="section">
 
<div id="reader-objects" class="section">
  
== Reader Objects ==
+
== 读者对象 ==
  
Reader objects ([[#csv.DictReader|<code>DictReader</code>]] instances and objects returned by the
+
Reader 对象([[#csv.DictReader|DictReader]] 实例和由 [[#csv.reader|reader()]] 函数返回的对象)具有以下公共方法:
[[#csv.reader|<code>reader()</code>]] function) have the following public methods:
 
  
; <code>csvreader.</code><code>__next__</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">csvreader.</span></span><span class="sig-name descname"><span class="pre">__next__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return the next row of the reader's iterable object as a list (if the object was returned from [[#csv.reader|<code>reader()</code>]]) or a dict (if it is a [[#csv.DictReader|<code>DictReader</code>]] instance), parsed according to the current dialect. Usually you should call this as <code>next(reader)</code>.
+
: 以列表(如果对象是从 [[#csv.reader|reader()]] 返回)或字典(如果是 [[#csv.DictReader|DictReader]] 实例)的形式返回下一行 reader 的可迭代对象,根据解析当前的 [[#csv.Dialect|方言]] 。 通常你应该把它称为 <code>next(reader)</code>
  
Reader objects have the following public attributes:
+
Reader 对象具有以下公共属性:
  
; <code>csvreader.</code><code>dialect</code>
+
; <span class="sig-prename descclassname"><span class="pre">csvreader.</span></span><span class="sig-name descname"><span class="pre">dialect</span></span>
: A read-only description of the dialect in use by the parser.
+
: 解析器使用的方言的只读描述。
  
; <code>csvreader.</code><code>line_num</code>
+
; <span class="sig-prename descclassname"><span class="pre">csvreader.</span></span><span class="sig-name descname"><span class="pre">line_num</span></span>
: 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 对象具有以下公共属性:
  
; <code>csvreader.</code><code>fieldnames</code>
+
; <span class="sig-prename descclassname"><span class="pre">csvreader.</span></span><span class="sig-name descname"><span class="pre">fieldnames</span></span>
: 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.
+
: 如果在创建对象时未作为参数传递,则在第一次访问或从文件中读取第一条记录时初始化此属性。
  
  
第379行: 第307行:
 
<div id="writer-objects" class="section">
 
<div id="writer-objects" class="section">
  
== Writer Objects ==
+
== 写入器对象 ==
  
<code>Writer</code> objects ([[#csv.DictWriter|<code>DictWriter</code>]] instances and objects returned by
+
<code>Writer</code> 对象([[#csv.DictWriter|DictWriter]] 实例和 [[#csv.writer|writer()]] 函数返回的对象)具有以下公共方法。 ''row'' 必须是 <code>Writer</code> 对象的字符串或数字的可迭代对象,以及将字段名映射到字符串或数字的字典(首先通过 [[../stdtypes#str|str()]] 传递它们) [[#csv.DictWriter|DictWriter]] 对象。 请注意,写出的复数被括号括起来。 这可能会导致其他读取 CSV 文件的程序出现问题(假设它们完全支持复数)。
the [[#csv.writer|<code>writer()</code>]] function) have the following public methods. A ''row'' must be
 
an iterable of strings or numbers for <code>Writer</code> objects and a dictionary
 
mapping fieldnames to strings or numbers (by passing them through [[../stdtypes#str|<code>str()</code>]]
 
first) for [[#csv.DictWriter|<code>DictWriter</code>]] objects. Note that complex numbers are written
 
out surrounded by parens. This may cause some problems for other programs which
 
read CSV files (assuming they support complex numbers at all).
 
  
 
<dl>
 
<dl>
<dt><code>csvwriter.</code><code>writerow</code><span class="sig-paren">(</span>''<span class="n">row</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">csvwriter.</span></span><span class="sig-name descname"><span class="pre">writerow</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">row</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Write the ''row'' parameter to the writer's file object, formatted according to
+
<dd><p>''row'' 参数写入编写器的文件对象,根据当前的 [[#csv.Dialect|方言]] 进行格式化。 返回调用底层文件对象的''write''方法的返回值。</p>
the current dialect. Return the return value of the call to the ''write'' method
 
of the underlying file object.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>Added support of arbitrary iterables.</p>
+
<p><span class="versionmodified changed"> 3.5 版更改: </span> 添加了对任意迭代的支持。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>csvwriter.</code><code>writerows</code><span class="sig-paren">(</span>''<span class="n">rows</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">csvwriter.</span></span><span class="sig-name descname"><span class="pre">writerows</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">rows</span></span>''<span class="sig-paren">)</span>
: 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'' 对象的迭代)中的所有元素写入编写器的文件对象,根据当前方言进行格式化。
  
Writer objects have the following public attribute:
+
Writer 对象具有以下公共属性:
  
; <code>csvwriter.</code><code>dialect</code>
+
; <span class="sig-prename descclassname"><span class="pre">csvwriter.</span></span><span class="sig-name descname"><span class="pre">dialect</span></span>
: A read-only description of the dialect in use by the writer.
+
: 作者使用的方言的只读描述。
  
DictWriter objects have the following public method:
+
DictWriter 对象具有以下公共方法:
  
 
<dl>
 
<dl>
<dt><code>DictWriter.</code><code>writeheader</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">DictWriter.</span></span><span class="sig-name descname"><span class="pre">writeheader</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Write a row with the field names (as specified in the constructor) to
+
<dd><p>将具有字段名称(在构造函数中指定)的行写入编写器的文件对象,根据当前方言进行格式化。 返回内部使用的 [[#csv.csvwriter.writerow|csvwriter.writerow()]] 调用的返回值。</p>
the writer's file object, formatted according to the current dialect. Return
 
the return value of the [[#csv.csvwriter.writerow|<code>csvwriter.writerow()</code>]] call used internally.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.2 新版功能.</span></p>
+
<p><span class="versionmodified added">3.2 版中的新功能。</span></p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.8 版更改: </span>[[#csv.DictWriter.writeheader|<code>writeheader()</code>]] now also returns the value returned by
+
<p><span class="versionmodified changed"> 在 3.8 版中更改: </span>[[#csv.DictWriter.writeheader|writeheader()]] 现在还返回它内部使用的 [[#csv.csvwriter.writerow|csvwriter.writerow()]] 方法返回的值。</p>
the [[#csv.csvwriter.writerow|<code>csvwriter.writerow()</code>]] method it uses internally.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第432行: 第349行:
  
 
<span id="csv-examples"></span>
 
<span id="csv-examples"></span>
== Examples ==
+
== 例子 ==
  
The simplest example of reading a CSV file:
+
读取 CSV 文件的最简单示例:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第440行: 第357行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv
+
<syntaxhighlight lang="python3">import csv
 
with open('some.csv', newline='') as f:
 
with open('some.csv', newline='') as f:
 
     reader = csv.reader(f)
 
     reader = csv.reader(f)
 
     for row in reader:
 
     for row in reader:
         print(row)</pre>
+
         print(row)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Reading a file with an alternate format:
+
读取具有替代格式的文件:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第455行: 第372行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv
+
<syntaxhighlight lang="python3">import csv
 
with open('passwd', newline='') as f:
 
with open('passwd', newline='') as f:
 
     reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
 
     reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
 
     for row in reader:
 
     for row in reader:
         print(row)</pre>
+
         print(row)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The corresponding simplest possible writing example is:
+
相应的最简单的写作示例是:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第470行: 第387行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv
+
<syntaxhighlight lang="python3">import csv
 
with open('some.csv', 'w', newline='') as f:
 
with open('some.csv', 'w', newline='') as f:
 
     writer = csv.writer(f)
 
     writer = csv.writer(f)
     writer.writerows(someiterable)</pre>
+
     writer.writerows(someiterable)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Since [[../functions#open|<code>open()</code>]] is used to open a CSV file for reading, the file
+
由于 [[../functions#open|open()]] 用于打开 CSV 文件进行读取,因此该文件将默认使用系统默认编码解码为 unicode(参见 [[../locale#locale|locale.getpreferredencoding()]])。 要使用不同的编码解码文件,请使用 open 的 <code>encoding</code> 参数:
will by default be decoded into unicode using the system default
 
encoding (see [[../locale#locale|<code>locale.getpreferredencoding()</code>]]). To decode a file
 
using a different encoding, use the <code>encoding</code> argument of open:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第487行: 第401行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv
+
<syntaxhighlight lang="python3">import csv
 
with open('some.csv', newline='', encoding='utf-8') as f:
 
with open('some.csv', newline='', encoding='utf-8') as f:
 
     reader = csv.reader(f)
 
     reader = csv.reader(f)
 
     for row in reader:
 
     for row in reader:
         print(row)</pre>
+
         print(row)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
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:
+
注册新方言:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第505行: 第418行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv
+
<syntaxhighlight lang="python3">import csv
 
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
 
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
 
with open('passwd', newline='') as f:
 
with open('passwd', newline='') as f:
     reader = csv.reader(f, 'unixpwd')</pre>
+
     reader = csv.reader(f, 'unixpwd')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
A slightly more advanced use of the reader --- catching and reporting errors:
+
阅读器的更高级用法——捕捉和报告错误:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第519行: 第432行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv, sys
+
<syntaxhighlight lang="python3">import csv, sys
 
filename = 'some.csv'
 
filename = 'some.csv'
 
with open(filename, newline='') as f:
 
with open(filename, newline='') as f:
第527行: 第440行:
 
             print(row)
 
             print(row)
 
     except csv.Error as e:
 
     except csv.Error as e:
         sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))</pre>
+
         sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
And while the module doesn't directly support parsing strings, it can easily be
+
虽然该模块不直接支持解析字符串,但可以轻松完成:
done:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第539行: 第451行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import csv
+
<syntaxhighlight lang="python3">import csv
 
for row in csv.reader(['one,two,three']):
 
for row in csv.reader(['one,two,three']):
     print(row)</pre>
+
     print(row)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Footnotes
+
脚注
 +
 
 +
; <span class="brackets">1</span><span class="fn-backref">([[#id3|1]],[[#id4|2]])</span>
 +
: 如果未指定 <code>newline=''</code>,嵌入在引用字段中的换行符将不会被正确解释,并且在使用 <code>\r\n</code> 写一个额外的 <code>\r</code> 的平台上将被添加。 指定 <code>newline=''</code> 应该始终是安全的,因为 csv 模块执行自己的 ([[../../glossary#term-universal-newlines|universal]]) 换行处理。
  
; <span class="brackets">1</span><span class="fn-backref">([[#id1|1]],[[#id2|2]])</span>
 
: If <code>newline=''</code> is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use <code>\r\n</code> linendings on write an extra <code>\r</code> will be added. It should always be safe to specify <code>newline=''</code>, since the csv module does its own ([[../../glossary#term-universal-newlines|<span class="xref std std-term">universal</span>]]) newline handling.
 
  
 +
</div>
  
 
</div>
 
</div>
 +
<div class="clearer">
 +
 +
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:51的最新版本

csv — CSV 文件读写

源代码: :source:`Lib/csv.py`



所谓的 CSV(逗号分隔值)格式是电子表格和数据库最常见的导入和导出格式。 在 RFC 4180 中尝试以标准化方式描述格式之前,CSV 格式已使用多年。 缺乏明确定义的标准意味着不同应用程序产生和使用的数据往往存在细微差别。 这些差异会使处理来自多个来源的 CSV 文件变得烦人。 尽管如此,虽然分隔符和引用字符各不相同,但整体格式足够相似,以至于可以编写一个可以有效操作此类数据的模块,从而对程序员隐藏读取和写入数据的细节。

csv 模块实现类以读取和写入 CSV 格式的表格数据。 它允许程序员说“以 Excel 首选的格式写入此数据”或“从 Excel 生成的此文件中读取数据”,而无需知道 Excel 使用的 CSV 格式的确切细节。 程序员还可以描述其他应用程序可以理解的 CSV 格式或定义自己的专用 CSV 格式。

csv 模块的 readerwriter 对象读取和写入序列。 程序员还可以使用 DictReaderDictWriter 类以字典形式读取和写入数据。

也可以看看

PEP 305 - CSV 文件 API
提议对 Python 进行此添加的 Python 增强提案。


模块内容

csv 模块定义了以下函数:

csv.reader(csvfile, dialect='excel', **fmtparams)

返回一个读取器对象,该对象将遍历给定的 csvfile 中的行。 csvfile 可以是任何支持 iterator 协议并在每次调用其 __next__() 方法时返回一个字符串的对象——file objects 和 list objects两者都合适。 如果 csvfile 是文件对象,则应使用 newline= 打开。 1 可以给出可选的 dialect 参数,用于定义特定于特定 CSV 方言的一组参数。 它可能是 Dialect 类的子类的实例,也可能是 list_dialects() 函数返回的字符串之一。 可以给出其他可选的 fmtparams 关键字参数来覆盖当前方言中的各个格式参数。 有关方言和格式参数的完整详细信息,请参阅 方言和格式参数 部分。

从 csv 文件读取的每一行都作为字符串列表返回。 除非指定了 QUOTE_NONNUMERIC 格式选项(在这种情况下未加引号的字段被转换为浮点数),否则不会执行自动数据类型转换。

一个简短的用法示例:

>>> 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)

返回一个 writer 对象,负责将用户的数据转换为给定的类文件对象上的分隔字符串。 csvfile 可以是具有 write() 方法的任何对象。 如果 csvfile 是文件对象,则应使用 newline= 1 打开。 可以给出可选的 dialect 参数,用于定义特定于特定 CSV 方言的一组参数。 它可能是 Dialect 类的子类的实例,也可能是 list_dialects() 函数返回的字符串之一。 可以给出其他可选的 fmtparams 关键字参数来覆盖当前方言中的各个格式参数。 有关方言和格式参数的完整详细信息,请参阅 方言和格式参数 部分。 为了尽可能容易地与实现 DB API 的模块交互,值 None 被写为空字符串。 虽然这不是可逆转换,但它可以更轻松地将 SQL NULL 数据值转储到 CSV 文件,而无需预处理从 cursor.fetch* 调用返回的数据。 所有其他非字符串数据在写入之前都使用 str() 进行字符串化。

一个简短的用法示例:

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]])
方言名称 相关联。 name 必须是字符串。 可以通过传递 Dialect 的子类或通过 fmtparams 关键字参数或两者来指定方言,并使用关键字参数覆盖方言的参数。 有关方言和格式参数的完整详细信息,请参阅 方言和格式参数 部分。
csv.unregister_dialect(name)
从方言注册表中删除与 name 关联的方言。 如果 name 不是已注册的方言名称,则会引发 Error
csv.get_dialect(name)
返回与 name 关联的方言。 如果 name 不是已注册的方言名称,则会引发 Error。 此函数返回一个不可变的 方言
csv.list_dialects()
返回所有已注册方言的名称。
csv.field_size_limit([new_limit])
返回解析器允许的当前最大字段大小。 如果给出 new_limit,这将成为新的限制。

csv 模块定义了以下类:

class csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

创建一个对象,其操作类似于常规阅读器,但将每一行中的信息映射到 dict,其键由可选的 fieldnames 参数给出。

fieldnames 参数是一个 序列 。 如果省略 fieldnames,则将使用文件 f 第一行中的值作为字段名。 不管如何确定字段名,字典都会保留它们的原始顺序。

如果一行的字段数多于字段名,则剩余的数据将放入一个列表中,并以 restkey(默认为 None)指定的字段名存储。 如果非空行的字段数少于字段名,则使用 restval 值(默认为 None)填充缺失值。

所有其他可选或关键字参数都传递给底层 reader 实例。

在 3.6 版更改:返回的行现在是 OrderedDict 类型。

在 3.8 版更改:返回的行现在是 dict 类型。

一个简短的用法示例:

>>> 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)

创建一个对象,其操作类似于常规编写器,但将字典映射到输出行。 fieldnames 参数是键的 序列,用于标识传递给 writerow() 方法的字典中的值写入文件 f 的顺序]。 可选的 restval 参数指定在字典缺少 fieldnames 中的键时要写入的值。 如果传递给 writerow() 方法的字典包含在 fieldnames 中找不到的键,则可选的 extrasaction 参数指示要采取的操作。 如果设置为 'raise'(默认值),则会引发 ValueError。 如果设置为 'ignore',则字典中的额外值将被忽略。 任何其他可选或关键字参数都传递给底层 writer 实例。

请注意,与 DictReader 类不同,DictWriter 类的 fieldnames 参数不是可选的。

一个简短的用法示例:

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

Dialect 类是一个容器类,其属性包含有关如何处理双引号、空格、分隔符等的信息。 由于缺乏严格的 CSV 规范,不同的应用程序生成的 CSV 数据略有不同。 Dialect 实例定义了 readerwriter 实例的行为方式。

所有可用的 Dialect 名称都由 list_dialects() 返回,它们可以通过它们的初始化程序注册到特定的 readerwriter 类( __init__) 功能如下:

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
class csv.excel
excel 类定义了 Excel 生成的 CSV 文件的常用属性。 它以方言名称 'excel' 注册。
class csv.excel_tab
excel_tab 类定义 Excel 生成的制表符分隔文件的常用属性。 它以方言名称 'excel-tab' 注册。
class csv.unix_dialect

unix_dialect 类定义了在 UNIX 系统上生成的 CSV 文件的常用属性,即 使用 '\n' 作为行终止符并引用所有字段。 它以方言名称 'unix' 注册。

3.2 版中的新功能。

class csv.Sniffer

Sniffer 类用于推断 CSV 文件的格式。

Sniffer 类提供了两种方法:

sniff(sample, delimiters=None)

分析给定的 sample 并返回反映找到的参数的 Dialect 子类。 如果给出了可选的 delimiters 参数,则它被解释为包含可能的有效分隔符的字符串。

has_header(sample)

分析示例文本(假定为 CSV 格式),如果第一行显示为一系列列标题,则返回 True

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 ...

csv 模块定义了以下常量:

csv.QUOTE_ALL
指示 writer 对象引用所有字段。
csv.QUOTE_MINIMAL
指示 writer 对象仅引用包含特殊字符的字段,例如 delimiterquotecharlineterminator 中的任何字符。
csv.QUOTE_NONNUMERIC

指示 writer 对象引用所有非数字字段。

指示读者将所有未引用的字段转换为类型 float

csv.QUOTE_NONE

指示 writer 对象从不引用字段。 当当前的 分隔符 出现在输出数据中时,它前面是当前的 escapechar 字符。 如果未设置 escapechar,则在遇到任何需要转义的字符时,编写器将引发 Error

指示 reader 不对引号字符进行特殊处理。

csv 模块定义了以下异常:

exception csv.Error
检测到错误时由任何函数引发。


方言和格式参数

为了更容易地指定输入和输出记录的格式,特定的格式参数被组合到方言中。 方言是 Dialect 类的子类,具有一组特定方法和一个 validate() 方法。 在创建 readerwriter 对象时,程序员可以指定一个字符串或 Dialect 类的子类作为方言参数。 除了或代替 dialect 参数,程序员还可以指定单独的格式化参数,这些参数与下面为 Dialect 类定义的属性具有相同的名称。

方言支持以下属性:

Dialect.delimiter
用于分隔字段的单字符字符串。 默认为 ','
Dialect.doublequote

控制如何引用字段内出现的 quotechar 实例本身。 当True时,字符加倍。 当 False 时,escapechar 用作 quotechar 的前缀。 默认为 True

在输出时,如果 doublequoteFalse 并且没有设置 escapechar,如果 quotecharError在一个领域找到。

Dialect.escapechar
如果 quoting 设置为 QUOTE_NONEquotechar 如果 双引号。 读取时,escapechar 会删除以下字符的任何特殊含义。 它默认为 None,禁用转义。
Dialect.lineterminator

用于终止由 writer 生成的行的字符串。 默认为 '\r\n'

笔记

reader 被硬编码以将 '\r''\n' 识别为行尾,并忽略 lineterminator。 这种行为将来可能会改变。

Dialect.quotechar
用于引用包含特殊字符(例如 delimiterquotechar)或包含换行符的字段的单字符字符串。 默认为 '"'
Dialect.quoting
控制何时应由作者生成引号并由读者识别。 它可以采用任何 QUOTE_* 常量(请参阅 模块内容 部分)并默认为 QUOTE_MINIMAL
Dialect.skipinitialspace
True 时,紧跟在 定界符 之后的空格将被忽略。 默认值为 False
Dialect.strict
True 时,在错误的 CSV 输入上引发异常 Error。 默认值为 False


读者对象

Reader 对象(DictReader 实例和由 reader() 函数返回的对象)具有以下公共方法:

csvreader.__next__()
以列表(如果对象是从 reader() 返回)或字典(如果是 DictReader 实例)的形式返回下一行 reader 的可迭代对象,根据解析当前的 方言 。 通常你应该把它称为 next(reader)

Reader 对象具有以下公共属性:

csvreader.dialect
解析器使用的方言的只读描述。
csvreader.line_num
从源迭代器读取的行数。 这与返回的记录数不同,因为记录可以跨越多行。

DictReader 对象具有以下公共属性:

csvreader.fieldnames
如果在创建对象时未作为参数传递,则在第一次访问或从文件中读取第一条记录时初始化此属性。


写入器对象

Writer 对象(DictWriter 实例和 writer() 函数返回的对象)具有以下公共方法。 row 必须是 Writer 对象的字符串或数字的可迭代对象,以及将字段名映射到字符串或数字的字典(首先通过 str() 传递它们) DictWriter 对象。 请注意,写出的复数被括号括起来。 这可能会导致其他读取 CSV 文件的程序出现问题(假设它们完全支持复数)。

csvwriter.writerow(row)

row 参数写入编写器的文件对象,根据当前的 方言 进行格式化。 返回调用底层文件对象的write方法的返回值。

3.5 版更改: 添加了对任意迭代的支持。

csvwriter.writerows(rows)
rows(如上所述的 row 对象的迭代)中的所有元素写入编写器的文件对象,根据当前方言进行格式化。

Writer 对象具有以下公共属性:

csvwriter.dialect
作者使用的方言的只读描述。

DictWriter 对象具有以下公共方法:

DictWriter.writeheader()

将具有字段名称(在构造函数中指定)的行写入编写器的文件对象,根据当前方言进行格式化。 返回内部使用的 csvwriter.writerow() 调用的返回值。

3.2 版中的新功能。

在 3.8 版中更改: writeheader() 现在还返回它内部使用的 csvwriter.writerow() 方法返回的值。


例子

读取 CSV 文件的最简单示例:

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

读取具有替代格式的文件:

import csv
with open('passwd', newline='') as f:
    reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
    for row in reader:
        print(row)

相应的最简单的写作示例是:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

由于 open() 用于打开 CSV 文件进行读取,因此该文件将默认使用系统默认编码解码为 unicode(参见 locale.getpreferredencoding())。 要使用不同的编码解码文件,请使用 open 的 encoding 参数:

import csv
with open('some.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

这同样适用于写入系统默认编码以外的其他内容:在打开输出文件时指定编码参数。

注册新方言:

import csv
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('passwd', newline='') as f:
    reader = csv.reader(f, 'unixpwd')

阅读器的更高级用法——捕捉和报告错误:

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))

虽然该模块不直接支持解析字符串,但可以轻松完成:

import csv
for row in csv.reader(['one,two,three']):
    print(row)

脚注

1(1,2)
如果未指定 newline=,嵌入在引用字段中的换行符将不会被正确解释,并且在使用 \r\n 写一个额外的 \r 的平台上将被添加。 指定 newline= 应该始终是安全的,因为 csv 模块执行自己的 (universal) 换行处理。