Writing data in a CSV file everytime a function is called

Viewed 33

I'm building an employee management system in which I've to write employees' data onto a file everytime the register system is called. Below I wrote it onto a text file. And it's working fine.

class Employee:
    def __init__(self, name, ID, password=None):

        self.name = name
        self.ID = ID
        self.password = password

   def register(self):
       self.password = input("Enter your password: ")

       database = open("Employees_data.txt", "a")
       database.write("\n"+self.name+","+self.ID+","+self.password)
       database.close()
       return "Registration successfully!"

But I've to write data on a CSV file instead. I tried the following code but everytime I call the function, the previous line of data is overwritten.

    def register(self):
        self.password = input("Enter your password: ")
        lst = [self.name, self.ID, self.password]
        with open("Database.csv", "w", newline="") as data_file:
            csv_writer = csv.writer(data_file, delimiter=",")
            csv_writer.writerow(lst)
        data_file.close()
        return "Registration successfully!"

What do I do about it?

1 Answers

At first just delete this line. You don't need it.

data_file.close()

When you are using context manager in python it closes the file when writing in the file is finished. after that, if you want to append your result to the file just instead of 'w' use 'a'

Related