Adding data from a list to csv columns that already have data

Viewed 73

I am new to Python, so I would like to ask:

I have a csv with two columns A and B.

A B
1 testa
2 testb

What I want to do is to add data to this CSV. I have the data which I want to add in a list in Python. This is mydata_list: [[3, 'testd'], [4, 'teste'], [5, 'testf'], [6, 'testg']]

How do I add this mydata_list to my csv columns, which already have data? I have been trying with something like this, but it doesn't work.

with open(filename, 'w') as file:
    writer = csv.DictWriter(file, fieldnames=["A", "B"])
    if row['A'] == 4:
        for e in mydata_list:
            writer.writerow(e)
1 Answers

you can use csv library for the same. Refer below:

# Importing library 
import csv 
  
# data to be written row-wise in csv file 
data = [[3, 'testd'], [4, 'teste'], [5, 'testf'], [6, 'testg']]
  
# opening the csv file in 'a+' mode 
file = open(filename, 'a+', newline ='') 
  
# writing the data into the file 
with file:     
    write = csv.writer(file) 
    write.writerows(data) 
Related