简体   繁体   中英

How to write to CSV using csv package in python line by line

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM