将类文件写入csv时出错

时间:2017-03-06 11:24:41

标签: python list csv dictionary

class Employee:
    def __init__(self, name, idno, leavetaken, leavereqd, reason):
        self.name = name
        self.idno = idno
        self.leavetaken = leavetaken
        self.leavereqd = leavereqd
        self.reason = reason

    def __str__(self):
        return "Name: {}\nID No:{}\nLeave Taken: {}\nLeave Requested: {}\nLeave Reason: {}\n".format(self.name, self.idno, self.leavetaken, self.leavereqd, self.reason)

n = int(raw_input("Please enter the number of employees: "))
employees = []

for i in range(n):
    employee = Employee(
        raw_input("Employee name: "),
        raw_input("Employee ID no: "),
        raw_input("Employee leave taken: ") ,

    raw_input("Employee leave requested: ") ,
        raw_input("Employee leave reason: ") 
    )
    employees.append(employee)

print("\n")

for employee in employees:
    print(employee)

我无法将输出保存到csv文件中。如果你能帮助我,那将是一个很大的帮助。

如果我尝试以下内容编写csv,我将键错误视为零

keys = my_li[0].keys()
with open('people.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(my_li)

我尝试过另一种方式将它们写成csv

keys = employee[0].keys()
with open('peo.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(employee)

我得到的错误是

  

AttributeError: Employee instance has no attribute 'getitem'

Listwriter功能也没有成功。任何人都可以给我解决方案将它们写成csv吗?

1 个答案:

答案 0 :(得分:1)

这应该为你做。

columns = ['name', 'idno', 'leavetaken', 'leavereqd', 'reason']
with open('peo.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, columns)
    dict_writer.writeheader()
    dict_writer.writerow({'name': employee.name, 'idno': employee.idno, ...})

遍历列表中的所有员工。