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.
# some init
return iter(self.name, self.my_value,self.my_datetime)
#from another class
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:
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(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.