Home > Software design >  How to append a list as row in csv file in python?
How to append a list as row in csv file in python?

Time:10-08

I intend to append following list into a csv file so that it appears in a single row but my code isn't working. I'm a beginner in python. Any suggestions would be welcome. Thank You.

list_one = ['apple','ball','cat','dog']

I tried following code:

import csv

list = ['apple','cat','dog']

with open('document.csv','a') as fd:
  fd.writerows(list)

CodePudding user response:

import csv

list = ['apple','cat','dog']

with open('document.csv','a') as fd:
  write = csv.writer(fd)   
  write.writerow(list)

CodePudding user response:

Explanation

Your implementation is wrong. fd don't have any properties writerow or writerows. To use writerow or writerows you have to initiate csv.writer().

Working Code:

import csv

list = ['apple','cat','dog']

with open('document.csv', 'w', newline="") as fd:
    writer = csv.writer(fd)
    writer.writerow(list)

CSV Output:

apple,cat,dog
  • Related