将数据对象列表转换为 csv
convert list of data object to csv
我正在使用 python 2.7.6。我想将我的对象列表转换为 csv 格式。我有一个 cdr 对象列表,这个对象包含一些字符串、int 和数据时间对象。
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)
但我收到的是空白 csv。感谢帮助。
iter
内置函数需要一个集合作为参数,因此以列表形式传递属性。然后使用@Shankar 的建议。
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
来自 python 帮助文档:
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.
我正在使用 python 2.7.6。我想将我的对象列表转换为 csv 格式。我有一个 cdr 对象列表,这个对象包含一些字符串、int 和数据时间对象。
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)
但我收到的是空白 csv。感谢帮助。
iter
内置函数需要一个集合作为参数,因此以列表形式传递属性。然后使用@Shankar 的建议。
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
来自 python 帮助文档:
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.