【问题标题】:how can my code 'pass' if it doesnt find a word in csv python如果在 csv python 中找不到单词,我的代码如何“通过”
【发布时间】: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


    【解决方案1】:

    虽然在语法上有效,但

    row['one'] and row['two'] and row['three'] not in row
    

    没有做你期望的事情。

    要检查 row 是否包含键 'one''two''three',请使用

    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 而不是 else 中)。

    【讨论】:

    • 您的代码几乎可以正常工作。它现在打印出 new_two,new_one,new_three 1,2,['three'] 2,3,['three'] 3,4,['three'] 而我希望输出为 new_two,new_one,new_three 1, 2 2,3 3,4
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2013-06-03
    相关资源
    最近更新 更多