2

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 Answer 1

1

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