krishna oadba
krishna oadba

Reputation: 13

How to print output to a csv file?

I need help in writing code to print output to csv file. The code is posted below. Appreciate your help.

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)

Upvotes: 1

Views: 25802

Answers (1)

blhsing
blhsing

Reputation: 106513

Use csv.writer to write the rows in result to an output stream:

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

Upvotes: 2

Related Questions