Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write a list of integer into csv row-wise

I am trying to write a list of float or int into a csvfile row-wise.

for some reason I am able to write them if the list are made up of strings

import csv
even_numbers = ['2','4','6','8'] # list of strings
header = ['even numbers']

with open('even_numbers.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(header)
    writer.writerows(even_numbers)

but when there are integers it throws an error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import csv
even_numbers = [2,4,6,8] # list of integers
header = ['even numbers']

with open('even_numbers.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(header)
    writer.writerows(even_numbers)

error

---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
<ipython-input-15-ae817296f34e> in <module>
      6     writer = csv.writer(csvfile)
      7     writer.writerow(header)
----> 8     writer.writerows(Even_list)

Error: iterable expected, not int

What other ways can I write a list to csv row-wise?

>Solution :

The writerows() method expects a list of lists. A row is a list and the rows are a list of those.

Two solutions, depending on what you want:

even_numbers = [[2, 4, 6, 8]]

or

even_numbers = [[2], [4], [6], [8]]

To do that latter transformation automatically, use:

rows = [[data] for data in even_numbers]
writer.writerows(rows)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading