将打印输出写入csv文件

时间:2018-07-04 15:50:43

标签: python python-3.x python-2.7

我需要编写代码以将输出打印到csv文件的帮助。该代码发布在下面。感谢您的帮助。

import csv

result = {}

with open('data.csv', 'rb') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',', quotechar='"')
    for row in csvreader:
        if row[0] in result:
            result[row[0]].append(row[1])
        else:
            result[row[0]] = [row[1]]

print result

1 个答案:

答案 0 :(得分:2)

使用csv.writerresult中的行写入输出流:

with open('output.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile)
    for row in result.items():
        csvwriter.writerow(row)