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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With