<p>我建议您使用Python的<code>csv</code>库来实现这一点,因为它将使事情变得更简单:</p>
<pre><code>import csv
hi = { 'ac':{'ab': 'a', 'po':'pb'},
'Tm':{'ab': 'a', 'po':'h'},
'ui':{'ab': 'b', 'po':'h'},
'zb':{'ab': 'f', 'po':'j'}}
with open('myData.tab', 'rb') as f_input, open('myData output.tab', 'wb') as f_output:
csv_input = csv.reader(f_input, delimiter='\t')
csv_output = csv.writer(f_output, delimiter='\t')
# Copy over the header to the output file and add the new column
csv_output.writerow(next(csv_input) + ['ab'])
for row in csv_input:
row.append(hi[row[4]]['ab'])
csv_output.writerow(row)
</code></pre>
<p>提供一个以制表符分隔的输出文件,并从输入csv文件中正确复制标题:</p>
<pre class="lang-none prettyprint-override"><code>Names names_id first second special_name ab
lili 1 a b Tm a
Katrin 2 c d Tm a
Paul 3 e f ui b
bob 4 g h zb f
tina 5 i j ac a
</code></pre>
<p><code>csv</code>库能够自动读取文件的每一行,并将其正确地转换为列表。当写回一个文件时,你所需要做的就是给它一个列表,它会在每个值之间自动添加必要的分隔符。当您需要处理可能包含分隔符本身的字符串时,这一点变得更加重要。你知道吗</p>