9

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.

kklw
  • 858
  • 3
  • 13
  • 28
  • https://docs.python.org/3/library/pickle.html is the way to go or you need to iterate through the attributes and then write to CSV. – Ankit Jaiswal May 23 '16 at 03:56
  • Have you tried plain simple list instead of cdr class first? the __iter__ function here is wrong (misuse if iter()), if it's actually ran, you should have an exception, instead of silent blank – tdihp May 23 '16 at 04:15
  • 1
    `iter()` function returns an iterable object. You have to use `.next()` to iterate over it or use a `list()` function to convert it to list... like `wr.writerow(list(cdr))` –  May 23 '16 at 04:33
  • 2
    It looks like `__iter__()` is supposed to be part of your class. If so, it would need to be indented, or it will be interpreted as its own function. – user20160 May 23 '16 at 05:07

1 Answers1

20

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.

slackmart
  • 4,754
  • 3
  • 25
  • 39