Reputation: 143
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)
I couldn't save the output yo a csv file. It would be a great help if u could help me.
If I try the following to write a csv, I'm getting key error as zero.
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)
I have tried another way to write them as 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)
and the error I'm getting is
AttributeError: Employee instance has no attribute 'getitem'
Listwriter
function wasn't successful too. Can anyone get me the solution to write them as csv?
Upvotes: 0
Views: 147
Reputation: 1181
This should do it for you.
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, ...})
Iterate through all employees in the list.
Upvotes: 1