convert list of data object to csv

kklw picture kklw · May 23, 2016 · Viewed 17.5k times · Source

I'm using python 2.7.6. I would like to convert my list of objects into csv format. I have a list of cdr object, this object contains some string, int and datatime object.

class cdr():
    def __init__(self):
        # some init

    def __iter__(self):
        return iter(self.name, self.my_value,self.my_datetime)

#from another class
import csv
def make_csv(self, cdr_list):
    with open(self.file_name, 'wb') as csv_file:
        wr = csv.writer(csv_file, delimiter=",")
        for cdr in cdr_list:
            wr.writerow(cdr)

But i'm getting a blank csv. Thanks for help.

Answer

slackmart picture slackmart · May 23, 2016

iter built-in function expects a collection as argument, so pass attributes in a list form. Then use the @Shankar suggestion.

class Cdr():

    def __iter__(self):
        return iter([self.name, self.my_value, self.my_datetime])


#from another class
with open(self.file_name, 'wb') as csv_file:
    wr = csv.writer(csv_file, delimiter=',')
    for cdr in cdr_list:
        wr.writerow(list(cdr))  # @Shankar suggestion

from python help docs:

iter(...)
iter(collection) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.