pythonfilewritefile

updating data in a file


I'm trying to write a code to do the following: I have a text file named students, each line(record) has: id,name,grade,number and gpa i'm trying to update the file and change the gpa(according to what the user enters in another function) I need first to find the id number of the student and then change his gpa.. When I'm using the write function, it's writing only the first line and the other lines get erased.. i'm not sure where is the problem.. any help is appreciated..

    file6=open("students.txt", 'r')
    students=[]
    for line3 in file6:
        students=line3.split(",")
        students[4]=students[4].rstrip('\n')
        if students[0]==str(x):
            gpa=str(gpa)
            del students[4]
            students.insert(4,gpa)
            print(students)
            for lines in file6:
                f=open("students.txt" ,'w')
                f.write(str(students[0])+',')
                f.write(str(students[1])+',')
                f.write(str(students[2])+',')
                f.write(str(students[3])+',')
                f.write(str(students[4])+'\n')
            break

Solution

  • Each function should have one well-defined role. Then, you can combine and reuse them in many different ways.

    def read_all(fn="students.txt"):
        students=[]
        for line in open(fn,'r'):
            students.append(line.strip().split(","))
        return students
    
    def write_all(rows, fn="students.txt"):
        f = open(fn,'w')
        for row in rows:
            print( ','.join(row), file=f )
    
    def replace_gpa(rows, key, gpa):
        for row in rows:
            if row[0] == key:
                row[4] = gpa
                return
    
    data = read_all()
    replace_gpa( "123", 4.0 )
    write_all( data )
    

    It would be even better to use the CSV module for this.

    import csv
    
    def read_all(fn="students.txt"):
        students=[]
        for row in cvs.reader(open(fn)):
            students.append(row)
        return students
    
    def write_all(rows, fn="students.txt"):
        with cvs.writer(open(fn,'w')) as fcsv:
            fcsv.writerows( rows )
    
    def replace_gpa(rows, key, gpa):
        for row in rows:
            if row[0] == key:
                row[4] = gpa
    
    data = read_all()
    replace_gpa( "123", 4.0 )
    write_all( data )