简体   繁体   English

将 integer 的列表逐行写入 csv

[英]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.我正在尝试将 float 或 int 列表逐行写入 csvfile。

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?我可以通过哪些其他方式逐行向 csv 写入列表?

The writerows() method expects a list of lists. writerows() 方法需要一个列表列表。 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.根据文档writeRows方法需要一个行对象列表作为参数。

You can also see the definition of a row object here .您还可以在此处查看行 object的定义。

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.对于 Writer 对象,行必须是字符串或数字的可迭代对象,对于 DictWriter 对象,必须是将字段名映射到字符串或数字的字典(首先通过 str() 传递它们)。

The reason you are getting this message is that it is trying to convert each int in that list as a row itself.您收到此消息的原因是它试图将该列表中的每个 int 转换为一行本身。 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.它可能会将每个数字拆分为行中的列,因为它将字符串作为行 object 读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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