简体   繁体   中英

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

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?

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)

According to the documentation , the writeRows method expects a list of row objects as a parameter.

You can also see the definition of a row object here .

That is:

A row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects.

The reason you are getting this message is that it is trying to convert each int in that list as a row itself. The reason it works for strings is that a string itself is iterable. However I suspect you would get unexpected behavior if you tried out a multiple digit number in your list of strings like this:

even_numbers = ['24','45','66','82'] # list of strings

It will likely split out each of the digits as columns in the row, because it is reading the string in as a row object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM