簡體   English   中英

CSV閱讀器:TypeError:+不支持的操作數類型:“ NoneType”和“ str”

[英]CSV Reader: TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

我有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'

當我嘗試再次嘗試該過程時,我遇到一個單獨的錯誤,指出它找不到其他密鑰(即,有一個名為“ firm”的密鑰,它將交換為現在是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)

我認為問題在於您正在使用utf-8編碼文件,但是在python中打開它們的方式就像它們是默認編碼一樣。 我不知道您的默認編碼是什么-它取決於您的系統和語言環境-但它可能不是utf-8。

最簡單的解決方法是不使用記事本重新編碼。

我認為您想將重組后的文件編寫為utf-8:但這很容易。 只需更改在寫入模式下打開文件的位置的語句即可指定encoding=utf-8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM