【发布时间】:2014-05-16 07:39:44
【问题描述】:
这是我的代码.csv
one,two #read the headers from here, and if the code finds headers,
1,2 #it takes the columns of the old headers, to the new headers in a new order.
2,3
3,4
例如,output.csv 如下所示:
new_two,new_one,new_three
2,1
3,2
4,3
请注意,两个之后缺少“,三”。这是我的python代码:
import csv
with open('code.csv', 'rb') as input, open('result.csv', 'wb') as output:
reader = csv.DictReader(input)
rows = [row for row in reader]
writer = csv.writer(output, delimiter = ',')
writer.writerow(["new_two", "new_one", "new_three"])
for row in rows:
if row['one'] and row['two'] and row['three'] not in row:
pass
else:
writer.writerow([row["one"], row["two"], row["three"]])
基本上,我希望我的代码始终包含这部分:writer.writerow([row["one"], row["two"], row["three"]]),它从输入文件标题中获取列,但如果它没有找到这些标题之一,我希望它忘记这一点并继续其余的列。
它给了我这个错误:
Traceback (most recent call last):
File "my_code.py", line 11, in <module>
if row['one'] and row['two'] and row['three'] not in row:
KeyError: 'three'
【问题讨论】:
标签: python csv if-statement conditional-statements