'How to write object to the file?

I am trying to do simple student management project in python. I am trying to do write objects to the file but it does not work. And when I try to write it just writes one student and it does not write to the next line.

class Student:
    def __init__(self,fname,lname,age,major):
        self.fname=fname
        self.lname=lname
        self.age=age
        self.major=major

    def accept(self,fname,lname,age,major):
        ls=[str(fname),str(lname),str(age),str(major)]
        with open('student.txt', 'w') as f:
                f.writelines(ls)


obj=Student('','','','')
obj.accept('Samet','Saricicek','21','student')
obj.accept('Emre','Saricicek','24','student')
obj.accept('Ezgi','Saricicek','25','student')


Solution 1:[1]

Here

with open('student.txt', 'w') as f:
        
        f.writelines(ls)

you opened file in w that is write mode, by doing so you are removing existing content of file, if you do not wish to do that use a (append) mode

with open('student.txt', 'a') as f:
        
        f.writelines(ls)

See open in Built-in Functions docs for further discussion of availables modes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daweo