0

I want to write data to a csv file row by row :

Please find the code below:

with open('a.csv',mode='w') as csv_file:
    fieldnames=['colA','colB','colC']
    writer=csv.DictWriter(csv_file,fieldnames=fieldnames)
    writer.write_row({'colA':data1,'colB':data2,'colC':data3})

The above code is inside a loop in which the data changes each time and i need to write to csv file in every loop. With this code my csv file is having only 1 line with the latest data. How do i modify the code to get multiple lines?

1 Answer 1

1

You're recreating the file and reinitializing the csv on each iteration. Instead, move the initialization outside the loop so that it only happens once.

with open('a.csv',mode='w') as csv_file:
    fieldnames=['colA','colB','colC']
    writer=csv.DictWriter(csv_file,fieldnames=fieldnames)
    for line in lines: # This is where your `for` loop should be relative to `with`
        writer.write_row({'colA':data1,'colB':data2,'colC':data3})
Sign up to request clarification or add additional context in comments.

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.