我试图调用open_and_read_file函数每当我需要在我的代码期间读取csv文件。我将它添加到我的代码中:
class EmployeesList(object):
def __init__(self, list_of_employees):
self.list_of_employees = list_of_employees
def open_and_read_file(self):
return pd.read_csv(self.list_of_employees)
def add_employee(self, new_employee):
list_of_employees_data = self.open_and_read_file()
for row in list_of_employees_data:
if new_employee.employee_id in row:
print(EMPLOYEE_ALREADY_EXISTS_MSG)
return
list_of_employees_data.write("{}, {}, {}, {}rn").format(str(new_employee.employee_id), new_employee.name,
str(new_employee.phone), str(new_employee.age))
显示了这个错误:
AttributeError: 'DataFrame' object has no attribute 'write'
你能告诉我如何将新数据附加到csv文件中吗?谢谢!
出现此错误是因为数据框架中没有写函数
检查此链接是否附加到pandas数据框架
此外,根据您的代码,属性list_of_employees不会被修改,因为没有"self"之前。否则你可以添加self或者用to_csv()
我将假设CSV具有以下头名称:
id, name, phone, age
有几种方法可以添加到Pandas数据框。您可以使用.append()
方法。
df.append({"id:" new_employee.employee_id, "name": new_employee.name, "phone": new_employee.phone, "age": new_employee.age})
或者您可以使用loc
属性来附加数据:
df.loc[len(df)] = [new_employee.employee_id, new_employee.name, new_employee.phone, new_employee.age]
请注意,我没有将数据转换为字符串,因为我假设它们将以其自然类型在csv和new_employee
对象中表示:
id, name, phone, age
1, "James", "555-666-777-888", 34
2, "David", "444-555-222-111", 33
3, "Julia", "222-333-333-333", 32
-> type(id) -> int
-> type(name) -> str
-> type(phone) -> int or str, whiche ever
-> type(age) -> int
如果你真的想把它们作为字符串,只需添加str()
函数。
如果您想要更新csv文件,请记住在最后执行以下操作:
df.to_csv((self.list_of_employees)