1

I want to write data onto several rows in a csv file. With this code I am only getting a single line written onto file. Need help.

for i in range(1,10):
    with open("output.csv",'wb') as f:
        writer = csv.writer(f, dialect='excel')
        writer.writerow([value1, value2, value3])
Rakesh Nittur
  • 445
  • 1
  • 7
  • 20

3 Answers3

3

You are encountering the error because it is re-writing a csv for every iteration in your loop. You should move the with open() statement outside of your loop block.

Jeff Mandell
  • 863
  • 7
  • 16
3

Try opening the file only once and then doing the loop:

with open("output.csv",'wb') as f:
    writer = csv.writer(f, dialect='excel')
    for item in list_A:
        writer.writerow([value1, value2, value3])
Alvaro Bataller
  • 487
  • 8
  • 29
1

You would need to use the w option in open as follows:

import csv
list_A = [0,0,0,0,0,0,0,0,0,0,0]
with open("output.csv",'w') as f:
    writer = csv.writer(f)
    for item in list_A:
        writer.writerow([1,0,0,0])
GigaWatts
  • 101
  • 8