1

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
krishna oadba
  • 13
  • 1
  • 1
  • 5
  • 3
    You probably don't want to use `print` in this way, you just want to use the `writer` method of the `csv` library. If this is your own code for `reader` then you have more than enough understanding to implement the `writer`. – roganjosh Jul 04 '18 at 15:53
  • https://docs.python.org/3.4/library/csv.html#csv.writer Check this out – NoorJafri Jul 04 '18 at 15:54
  • what are you trying to achieve and what have you tried already? – Janko Jul 04 '18 at 15:55
  • 1
    Provide sample input and desired output. – user2390182 Jul 04 '18 at 15:56
  • i am new to python,i used this sample code from other post to replicate my scenario, – krishna oadba Jul 04 '18 at 16:01
  • import csv result = {} with open('dataout.csv', 'w') as new_file: fieldnames = ['col1','col2'] csv_writer = csv.writer(new_file,lineterminator='\n') with open('data.csv', 'r') 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) csv_writer.writerows(result) – krishna oadba Jul 04 '18 at 16:02
  • so far i have this – krishna oadba Jul 04 '18 at 16:03
  • please update the question. – Matthew Story Jul 04 '18 at 16:05

1 Answers1

2

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)
blhsing
  • 91,368
  • 6
  • 71
  • 106