如何检查csv文件中是否已存在行?

2024-03-29 13:46:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将员工转换为员工csv文件,除非我已经在那里有了他的数据。在这种情况下,我想向用户提出一个错误。当我运行代码时,我没有得到任何错误,但是也没有添加员工。 谢谢你的帮助

import csv

class Employee(object):

    def __init__(self, employee_id, name, phone, age):
        self.employee_id = employee_id
        self.name = name
        self.phone = phone
        self.age = age

class Employees_list(object):

    def __init__(self, list_of_employees):
        self.list_of_employees = list_of_employees

    def add_employee(self, new_employee):
        new_employee_data = [new_employee.employee_id, new_employee.name, new_employee.phone, new_employee.age]
        with open(self.list_of_employees) as file1:
            existing_lines = csv.reader(file1)
            for row in existing_lines:
                if row not in new_employee_data:
                    new_employee_data.append(row)
                else:
                    print("Sorry, the employee is already exist.")

Tags: ofcsvnameselfidnewagedata
1条回答
网友
1楼 · 发布于 2024-03-29 13:46:30

你把对比倒过来了if row not in new_employee_data询问现有员工的整行是否在任何一条新员工信息中。而是询问新员工是否在任何现有行中。我将支票移到了with之外。一旦您阅读了csv,就没有必要将其打开

    def add_employee(self, new_employee):
        new_employee_data = [new_employee.employee_id, new_employee.name, new_employee.phone, new_employee.age]
        with open(self.list_of_employees) as file1:
            existing_lines = csv.reader(file1)
        if new_employee_data not in existing_lines:
            new_employee_data.append(row)
            # todo: save the new csv
        else:
            print("Sorry, the employee is already exist.")

当然,请注意,如果新员工信息和现有员工信息在拼写上存在任何差异,则此操作将失败

相关问题 更多 >