Home > Net >  How to write object to the file?
How to write object to the file?

Time:03-19

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')

CodePudding user response:

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.

CodePudding user response:

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', 'a') as f:
            
           for line in ls:
               
              f.write(line '\t')
           f.write('\n')

def search(fname,lname):
    
    with open('student.txt','r') as f:
        
        data=f.readlines()
        
        for line in data:
            if fname and lname in line:
                print(line)

def searchage():
    
    with open('student.txt','r') as f:
        
        lines = [line.rstrip() for line in f]
        print(lines)



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

Sir i want to search by name and add them to list. When i use rstrip it returns all of the contents to the list. But i just want one line to return as a list.How can i do that?

  • Related