Skip to content
Advertisement

Extract inner list content and write to csv with writerow loop

How do I write only content of the inner loop in rows to csv file?

lst=[['apple'], ['banana'], ['cantaloupe'], ['durian']]
f = writer(open("abcd.file", 'w', newline = ''), delimiter=",")
for row in lst:
   f.writerow(["xoxo", row, '', '', '', ''])

got:

xoxo,['apple'],,,,
xoxo,['banana'],,,,
xoxo,['cantaloupe'],,,,
xoxo,['durian'],,,,

want in abcd.file:

xoxo,apple,,,,
xoxo,banana,,,,
xoxo,cantaloupe,,,,
xoxo,durian,,,,

Advertisement

Answer

your lst is a list inside a list, so in order to print the item inside you need to use [0]

try this:

lst=[['apple'], ['banana'], ['cantaloupe'], ['durian']]
f = writer(open("abcd.file", 'w', newline = ''), delimiter=",")
for row in lst:
   f.writerow(["xoxo", row[0], '', '', '', ''])
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement