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])

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And the creation of the csv.writer should be outside the loop for that matter (it would probably work without that change, but rebuilding the writer over and over is slow/wasteful).
Is there a way I can append the data without overwriting it?
yes. There is a post by Alvaro here that shows the code
I changed it to "with open("output.csv",'a') as f:" and it solved the problem!
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])

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.