CSV Reader:TypeError:不支持的操作数类型+:' NoneType'和' str'

时间:2015-07-28 21:54:54

标签: python csv python-3.x

我的CSV阅读脚本突然遇到问题。我的工作流程是我使用csv列出信息行,使用记事本将其转换为utf-8。然后我在上面运行这段代码。

现在我开始收到以下错误:

Traceback (most recent call last):
File "C:\Users\x\x\x\uploader\user_db_and_upload.py", line 121, in <module>
csv_dict_reader(f_obj, x_obj, n_obj)
File "C:\Users\x\x\x\uploader\user_db_and_upload.py", line 57, in csv_dict_reader
name = data_in_list[x]['firstname'] + " " + data_in_list[x]['surname']
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

当我尝试再次尝试这个过程时,我遇到一个单独的错误,说它找不到一个不同的密钥(其中一个密钥称为&#39; firm&#39;它会交换说现在是KeyError,它无法找到它。)

我想我很困惑的是,如果我将它转换为utf-8并且没有更改任何代码,为什么我发现自己处于这个位置。原始代码是错的吗?一切都会有所帮助。

代码:

def csv_dict_reader(file_obj, x_obj, n_obj):

    data_in_list = []
    x=0

    reader = csv.DictReader(file_obj, delimiter=',')
    f = csv.writer(x_obj, delimiter=',', quotechar='"')
    f1= csv.writer(x_obj, delimiter=',', quotechar='"')
    f2= csv.writer(n_obj, delimiter=',', quotechar='"')

    f1.writerow(["name","email","external_id","details","notes","phone","role","restriction","organization","tags"])
    f2.writerow(["name","email","phone","office","department", "role"])

    for row in reader:
        data_in_list.append(row)

        name = data_in_list[x]['firstname'] + " " + data_in_list[x]['surname']
        firm = data_in_list[x]['firm']
        phone = data_in_list[x]['phone']
        email = data_in_list[x]['email']
        office = data_in_list[x]['office']
        department = data_in_list[x]['dept']
        details = ","
        notes = ","
        role = data_in_list[x]['role']
        restrictions = ","
        tags = ","

        f.writerow([name] + [email] + [details] + [phone] + [role] + 
               [restrictions] + [firm] + [tags] + [office] + [department])
        f2.writerow([name] + [email] + [phone] + [office] + [department] + [role])

        x= x+1
    return data_in_list

if __name__ == "__main__":

    with open("stafflist11.csv") as f_obj:
        with open("new.csv", "w") as x_obj:
            with open("user_databse_nepo.csv", "w") as n_obj:   
                csv_dict_reader(f_obj, x_obj, n_obj)

1 个答案:

答案 0 :(得分:0)

我认为问题在于你是在utf-8中对文件进行编码,而是在python中打开它们,就好像它们是你的默认编码一样。我不知道你的默认编码是什么 - 它取决于你的系统和语言环境 - 但它可能不是utf-8。

最简单的解决办法就是不要使用记事本重新编码。

我认为你想把重组后的文件写成utf-8:但这很容易。只需更改以写入模式打开文件的语句,以指定encoding=utf-8