Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: dict contains fields not in fieldnames

Tags:

python

csv

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.

like image 301
akbsmile Avatar asked Nov 15 '14 09:11

akbsmile


1 Answers

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 = ';') 
like image 121
Tim Pietzcker Avatar answered Oct 21 '22 03:10

Tim Pietzcker