Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

python - ValueError: dict contains fields not in fieldnames

Can someone help me with this.

I have my Select query

selectAttendance = """SELECT * FROM table """

And I want the content of my select query and include a header when I download the csv file, So I did this query:

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()

but it gives me this error

**ValueError: dict contains fields not in fieldnames**

I want to have like this output in my downloaded csv file:

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

Thank you in advance.

question from:https://stackoverflow.com/questions/26944274/valueerror-dict-contains-fields-not-in-fieldnames

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the error message clearly states, your dictionary contains keys that don't have a corresponding entry in your fieldnames parameter. Assuming that these are just extra fields, you can ignore them by using the extrasaction parameter during construction of your DictWriter object:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...