这是我的代码.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'
最佳答案
虽然语法上有效,但
row['one'] and row['two'] and row['three'] not in row
没有做你期望的事情。
检查row
是否包含键'one'
、'two'
和'third'
,使用
if 'one' in row and 'two' in row and 'three' in row:
writer.writerow([row['one'], row['two'], row['three']])
如果您想知道原始代码,if
会被解析为
if (row['one']) and (row['two']) and (row['three'] not in row):
换句话说,row['one']
和 row['two']
被视为通过 AND 组合在一起的单独表达式。这显然不是你想要的。此外,您已经将 AND 和 OR 混合在一起了(我的版本使用 AND,因为我反转了检查,将 writerow()
放在 if
中,而不是放在 if
中。 其他
)。
关于python - 如果我的代码在 csv python 中找不到单词,它怎么会是 'pass',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22855211/