将数据写入csv不起作用

时间:2016-02-26 16:41:36

标签: python python-2.7 csv

我正在使用Python v2.7。

我已经定义了一个School类,它有一个方法get_properties_in_array(),它返回一个属性数组:

class School:
   def __init__(self, name, address):
       self.name = name
       self.address = address

   def get_properties_in_array(self):
       return [self.name, self.address]

我创建了一所学校并将其添加到列表中:

school_list = []
my_school = School("school-name","school-address")
school_list.append(my_school)

然后,我尝试将此my_school写入CSV文件,其中属性已标签分隔(我已导入csv模块):

with open("schools.csv", 'w') as data_file:
     writer = csv.writer(data_file, delimiter='\t')
     for one_school in school_list:
         data = one_school.get_properties_in_array
         # TypeError: 'instancemethod' object has no attribute '__getitem__'
         writer.writerow(data)

但是当我运行它时,在行writer.writerow(data)中发生以下错误:

TypeError: 'instancemethod' object has no attribute '__getitem__'

为什么呢?怎么解决?

1 个答案:

答案 0 :(得分:2)

您需要调用方法

data = one_school.get_properties_in_array()