Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List to csv in python with header [closed]

I have written a script which gives the list like below as an output.

['red', '361', '0']
['blue', '1', '0']
['orange', '77', '0']
['cream', '660', '73']
['ivory', '159', '0']

This list is very huge and I want to write the output contents to a csv with header on top like below.

color | total | fail

Here is how I am trying to achieve it

with open('colour.csv', 'wb') as csvfile:
    header = ['color', 'total', 'fail']
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerow(header)
    for row in output:
        writer.writerow(output)

But the output I am getting is not as expected. The csv is generated and the last row of the list is printed thrice to the csv. I am not able to find why not all other rows are printed or why last row is printed thrice? Here is the sample output I am getting:

color | total | fail
ivory | 159 | 0
ivory | 159 | 0
ivory | 159 | 0

This is what I am expecting the output to be:

color | total | fail
red | 361 | 0 
blue | 1 | 0
orange | 77 | 0
cream | 660 | 73
ivory | 159 | 0

Can anyone please help me with this?

like image 591
csvb Avatar asked May 21 '16 18:05

csvb


1 Answers

Code -

import csv

arr = [['red', '361', '0'],
      ['blue', '1', '0'],
      ['orange', '77', '0'],
      ['cream', '660', '73'],
      ['ivory', '159', '0']]

with open('output.csv','w') as f:
    writer = csv.writer(f)
    writer.writerow(['color', 'total', 'fail'])
    writer.writerows(arr)
like image 83
Vedang Mehta Avatar answered Nov 14 '22 21:11

Vedang Mehta