python - Writing multiple items to a row in csv using for loop
问题描述
Suppose now I have a date and a list of groups(group A, group B, etc.) and would like to write all of them in one row in a CSV file. I have tried the following code but there are several problems.
import csv
with open('test.csv', 'w') as file:
output = csv.writer(file)
output.writerow('Date')
for i in range(0,len(c)):
output.writerow([lst[i]]) #lst is the list containing the group number
The output here is
D a t e
Group A
Group B
Group C
The first issue is that each character in Date
is treated separately, each of them appears in separate columns.
The second issue is that there is a new line between each row which is not desired.
Lastly, instead of writing them in rows, I want them to be in one row with multple columns. The ideal output should be as follows
Date Group A Group B Group C
解决方案
You need to combine all the elements you want included in the row into a single list:
import csv
with open('test.csv', 'w') as file:
output = csv.writer(file)
out = ['Date']
for i in range(0,len(c)):
out.append(lst[i])
output.writerow(out)
推荐阅读
- javascript - Angular 11 - 将不同样式的图标添加到自定义按钮组件
- python - 在Django中编写外部SQL文件的常规方法是什么
- php - Elasticsearch - 按字段获取结果摘要
- julia - 无法在 Julia 中安装任何软件包
- java - (Java) 如何在没有辅助函数的情况下从不断增加的堆栈帧返回 -1?
- awk - 使用 sed 搜索降价
- python - 将列表值列表分组到相等距离的 bin 中
- scroll - 如何在没有下一页信息的情况下使用带有无限循环的scrapy进行抓取
- flutter - 如何解决颤振中的“文本溢出.椭圆”?
- swift - Swift How To - First/Where 语句检查可选对象数组 - 展开和匹配