Home > Net >  exporting list into a csv file using python
exporting list into a csv file using python

Time:04-29

first of all im still learning python and im having a good time so far. while learning I ran into this issue I have a variable named MyList as follows

MyList = [{'orange', 'Lemon'},
 {'Apple', 'Banana', 'orange', 'Lemon'},
 {'Banana', 'Lemon'},
 {'Apple', 'orange'}]

I want to dump the list in a csv file in a rows as the same order as above so the csv will be like:

 orange   Lemon
 Apple    Banana   orange   Lemon 
 Banana   Lemon 
 Apple    orange 

so I put the command bellow

MyList.to_csv("MyList.csv", sep='\t', encoding='utf-8')

however it gives me the following error

AttributeError: 'list' object has no attribute 'to_csv'

CodePudding user response:

You need to convert the list object into csv object.

import csv

with open('MyList.csv', 'w', newline='') as myfile:
     wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
     wr.writerows(MyList)

Refer the following question by Fortilan Create a .csv file with values from a Python list

CodePudding user response:

You'll need to use the csv module and open a file for write:

import csv

MyList = [{'orange', 'Lemon'},
 {'Apple', 'Banana', 'orange', 'Lemon'},
 {'Banana', 'Lemon'},
 {'Apple', 'orange'}]

with open('MyList.csv', 'w') as f:
      
    # using csv.writer method from csv module
    write = csv.writer(f)
    write.writerows(MyList)
  • Related