python - 如果我的代码在 csv python 中找不到单词,它怎么会是 'pass'

标签 python csv if-statement conditional-statements

这是我的代码.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/

相关文章:

python - 通过 tweepy 从 django 表单将图像上传到 Twitter

javascript - 使用 BeautifulSoup 进行网页抓取不起作用

javascript - 不懂这个JS

javascript - 在 if 语句中使用 "!!"不是多余的吗,因为 if 语句已经检查是否为真?

r - R 中 ifelse() 的奇怪行为 : when are the values evaluated?

python - Numpy reshape 矩阵

python - 如何根据星期几求平均值

python - csv 上传时自定义 Django 管理页面出错(对象没有属性 'model' )

Python 内存错误 : cannot allocate array memory

xml - wso2 esb 文件处理示例 smooks csv 解析器第一行包括有效负载命名空间