【问题标题】:writing a list with multiple data to a csv file in separate columns in python在python的不同列中将包含多个数据的列表写入csv文件
【发布时间】:2015-04-05 22:07:16
【问题描述】:
import csv
from itertools import izip
    if l > 0:
            for i in range(0,l):
        combined.append(str(questionList[i]).encode('utf-8') + str(viewList[i]).encode('utf-8'))
#       viewcsv.append(str(viewList[i]).encode('utf-8'))
#       quescsv.append(str(questionList[i]).encode('utf-8'))
        with open('collect.csv', 'a') as csvfile:
             spamwriter = csv.writer(csvfile, delimiter='\n')
             spamwriter.writerow(combined)
#            spamwriter.writerows(izip(quescsv, viewcsv))
        return 1
    else:
        return 0

我需要生成一个 csv 文件,并将来自 2 个或更多列表的数据填充到单独的列中,而不是单个列中。目前我正在尝试将两个列表组合在一个列表中(组合)并将其用作写入的输入,但我没有得到想要的 o/p。 我尝试了很多方法,包括字段名方式,izip 方式,但徒劳无功。 例如: questionList viewList 4 3 次观看 5 0 次观看

所使用的数字只是举例。

【问题讨论】:

  • 你能写一个输入数据和预期输出文件的例子吗?

标签: python-2.7 export-to-csv scrape


【解决方案1】:

你可能需要这样的东西:

import csv

X = [1, 2, 3, 4, 5]
Y = [2, 3, 5, 7, 11]
Z = ['two', 'three', 'five', 'seven', 'eleven']

with open('collect.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for row in zip(X, Y, Z):
        writer.writerow(row)

【讨论】:

  • 解决方案不满足要求。它写在同一列中,我的查询是写在不同的列中。
【解决方案2】:
import csv

X = [1, 2, 3, 4, 5]
Y = [2, 3, 5, 7, 11]
Z = ['two', 'three', 'five', 'seven', 'eleven']

with open('collect.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')

    writer.writerow(X)
    writer.writerow(Y)
    writer.writerow(Z)

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2018-04-02
    • 2017-01-04
    相关资源
    最近更新 更多