<ol>
<li>从<code>csv.reader</code>读取的所有数据都是字符串。在</li>
<li><p>对此有多种解决方案,但最简单的方法是在<code>(</code>上拆分并去掉所有空白:</p>
<pre><code>>>> a = 'Toronto (Ont.)'
>>> b = a.split('(')
>>> b
Out[16]: ['Toronto ', 'Ont.)']
>>> c = b[0]
>>> c
Out[18]: 'Toronto '
>>> c.strip()
Out[19]: 'Toronto'
</code></pre>
<p>或者在一行中:</p>
^{pr2}$
<p>另一个选择是使用正则表达式(<a href="http://docs.python.org/2/library/re.html" rel="nofollow">re module</a>)。</p></li>
</ol>
<p>代码中的具体问题如下:</p>
<pre><code>f.write("%s %s"%line[1],%line[5])
</code></pre>
<p>使用<code>%</code>语法格式化字符串,必须提供单个值或iterable。在您的情况下,这应该是:</p>
<pre><code>f.write("%s %s" % (line[1], line[5]))
</code></pre>
<p>另一种完全相同的方法是使用<a href="http://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">^{<cd4>}</a>方法。在</p>
<pre><code>f.write('{} {}'.format(line[1], line[5]))
</code></pre>
<p>这是格式化字符串的一种灵活方法,我建议您阅读<a href="http://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">docs</a>中的相关内容。在</p>
<hr/>
关于你的代码,有两件事你应该考虑。在</p>
<ul>
<li><p>始终记住关闭文件处理程序。如果您使用<code>with open(...) as fp</code>,这将由您负责。在</p>
<pre><code>with open('myfile.txt') as ifile:
# Do stuff
# The file is closed here
</code></pre></li>
<li><p>不要使用保留字作为变量名。<code>file</code>就是这样一个东西,如果将其用作其他东西(<em>隐藏</em>it),您可能会在以后的代码中引起问题。</p></li>
<li><p>要写入数据,可以使用<a href="http://docs.python.org/2/library/csv.html#csv.writer" rel="nofollow">csv.writer</a>:</p>
<pre><code>with open('myfile.txt', 'wb') as ofile:
writer = csv.writer(ofile)
writer.writerow(['my', 'data'])
</code></pre></li>
<li><p>在Python2.6及更高版本中,您可以在一个语句中组合多个<code>with</code>语句:</p>
<pre><code>with open('raw.csv') as ifile, open('NicelyDone.text','w') as ofile:
reader = csv.reader(ifile)
writer = csv.writer(ofile)
</code></pre></li>
</ul>
<p>结合这些知识,您的脚本可以重写为:</p>
<pre><code>import csv
with open('raw.csv') as ifile, open('NicelyDone.text', 'wb') as ofile:
reader = csv.reader(ifile)
writer = csv.writer(ofile, delimiter=' ')
for row in reader:
city, num = row[1].split('(')[0].strip(), row[5]
writer.writerow([city, num])
</code></pre>