擅长:python、mysql、java
<p>要清除关于错误的混淆:您得到它是因为<code>r.fieldnames</code>只在第一次使用<code>r</code>从输入文件读取时设置。因此,您编写它的方式,<code>fieldnames</code>将始终初始化为<code>None</code>。</p>
<p>只有在从<code>r</code>中读取第一行之后,才能使用<code>r.fieldnames</code>初始化<code>w = csv.DictWriter(united, fieldnames=fieldnames)</code>,这意味着您必须重新构造代码。</p>
<p>此行为记录在<a href="http://docs.python.org/library/csv.html#csv.csvreader.fieldnames" rel="noreferrer">Python Standard Library documentation</a></p>
<blockquote>
<p>DictReader objects have the following public attribute:</p>
<p>csvreader.fieldnames</p>
<p>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.</p>
</blockquote>