2017-03-06 62 views
0
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

如果我嘗試以下寫入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嗎?

+0

糟糕。在嘗試縮進時,我給出了代碼,並且它已經在我的代碼中創建了>符號。 – anonymous

+0

最後一行不應該是dict_writer.writerows(employee [0])? – Kewl

+0

在keys = employee [0] .keys()中獲取錯誤,該僱員實例沒有屬性getitem – anonymous

回答

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, ...}) 

迭代列表中的所有員工。

+0

python輸出顯示了2名員工的詳細信息,當我給n = 2但csv只顯示最後一個。我哪裏出錯了? – anonymous

+0

這個實現使用了'writerow',它編寫了一個單行的對象(一個字典)。所以每次打開文件時都會寫入該行。你可以使用'writerows([dictionaries])'來代替所有員工。 – nir0s

+0

我在編寫代碼時嘗試寫字典時出現錯誤。你能解釋一下嗎? – anonymous