ValueError:dict包含不在fieldname中的字段

akb*_*ile 24 python csv

有人可以帮我弄这个吗.

我有我的Select查询

selectAttendance = """SELECT * FROM table """
Run Code Online (Sandbox Code Playgroud)

我想要我的选择查询的内容,并在下载csv文件时包含一个标题,所以我做了这个查询:

with open(os.path.join(current_app.config['UPLOAD_FOLDER'], 'csv.csv'), 'wb') as csvfile:
                writer = csv.DictWriter(csvfile,fieldnames  = ["Bio_Id","Last_Name","First_Name","late","undertime","total_minutes", "total_ot", "total_nsd", "total_absences"], delimiter = ';')
                writer.writeheader()
                writer.writerow(db.session.execute(selectAttendance))
            db.session.commit()
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误

**ValueError: dict contains fields not in fieldnames**
Run Code Online (Sandbox Code Playgroud)

我想在我下载的csv文件中输出这个输出:

Bio_Id Last_Name First_Name late undertime total_minutes total_ot total_nsd total_absences
1      Joe       Spark       1     1            2            1        1          1
Run Code Online (Sandbox Code Playgroud)

先感谢您.

Tim*_*ker 100

正如错误消息明确指出的那样,您的字典包含在fieldnames参数中没有相应条目的键.假设这些只是额外的字段,您可以在构造对象时使用extrasaction参数DictWriter忽略它们:

writer = csv.DictWriter(csvfile, fieldnames=["Bio_Id","Last_Name","First_Name","late","undertime","total_minutes", "total_ot", "total_nsd", "total_absences"], 
                        extrasaction='ignore', delimiter = ';')
Run Code Online (Sandbox Code Playgroud)


bgu*_*ach 15

正如错误所述:来自查询的字典包含的密钥多于您在DictWriter构造函数中指定的字段名称.

一种解决方案是提前过滤,如下所示:

field_names = ["Bio_Id","Last_Name", ...]
writer = csv.DictWriter(csvfile,fieldnames=field_names , delimiter = ';')
writer.writeheader()
data = {key: value for key, value in db.session.execute(selectAttendance).items()
        if key in field_names}
writer.writerow(data)
Run Code Online (Sandbox Code Playgroud)

另一种解决方案可能是仅使用以下字段构造查询:

query = 'SELECT %s FROM table' % ', '.join(field_names)
Run Code Online (Sandbox Code Playgroud)

然而,Tim Pietzcker的答案是最好的.