Continuously write data from a list into a CSV file
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC O Beethoven - Piano Sonata No 3 in C
--
Chapters
00:00 Question
01:59 Accepted answer (Score 3)
02:53 Thank you
--
Full question
https://stackoverflow.com/questions/4701...
Question links:
[Writing List of Strings to Excel CSV File in Python]: https://stackoverflow.com/questions/6916...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #csv #raspberrypi #raspbian
#avk47
--
Track title: CC O Beethoven - Piano Sonata No 3 in C
--
Chapters
00:00 Question
01:59 Accepted answer (Score 3)
02:53 Thank you
--
Full question
https://stackoverflow.com/questions/4701...
Question links:
[Writing List of Strings to Excel CSV File in Python]: https://stackoverflow.com/questions/6916...
--
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])