Rose
Rose

Reputation: 13

How do I check if a row already exists in a csv file?

I'm trying an employee to employees csv file, unless I already have his data there. In tht case, I want to raise an error to the user. When I run the code I don't get any error but the employee is not added as well. Thanks for any help!

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.")

Upvotes: 0

Views: 2016

Answers (1)

tdelaney
tdelaney

Reputation: 77347

You got the comparison backwards. if row not in new_employee_data asks if the entire row of an existing employee is in any single piece of new employee information. Instead ask if the new employee is in any existing rows. I moved the check outside of the with. Once you've read the csv, there is no need to keep it open.

    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.")

Notice of course that if there are any differences in spelling the new and existing employee informtion, this will fail.

Upvotes: 1

Related Questions