Search code examples
pythonpandasdataframecsvexport-to-csv

exporting list into a csv file using python


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'

Solution

  • 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