user2014905 user2014905 - 7 months ago 37
Python Question

convert list of data object to csv

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.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:

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


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.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(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.