Continuously write data from a list into a CSV file
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over
--
Chapters
00:00 Continuously Write Data From A List Into A Csv File
01:01 Accepted Answer Score 3
01:36 Thank you
--
Full question
https://stackoverflow.com/questions/4701...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #csv #raspberrypi #raspbian
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over
--
Chapters
00:00 Continuously Write Data From A List Into A Csv File
01:01 Accepted Answer Score 3
01:36 Thank you
--
Full question
https://stackoverflow.com/questions/4701...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #csv #raspberrypi #raspbian
#avk47
ACCEPTED ANSWER
Score 3
The writerows method of the csv module expects a nested list where each inner list represents the data for a single row. In your case, passing a flat list, it instead finds an int value at the 0th index where it's instead expecting the inner list for the first row. That explains the error message.
So, you should instead be using writerow each time you call your method. However, opening the file in write mode ('w') will delete all the contents of the file each time. Therefore, you need to open the file in append mode. A toy example:
import csv
def write_csv(data):
with open('example.csv', 'a') as outfile:
writer = csv.writer(outfile)
writer.writerow(data)
for x in range(5):
write_csv([x, x+1])