CSC111 Class Exercise Sketch

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 11:50, 8 December 2011 (EST)


text="""
alex toz,  3.8, 2012
jo s. grant, 3.9, 2013


"""
class Students:
    def __init__( self, fileName ):
        self.fileName = fileName
        file = open( fileName, 'r' )
        lines = file.readlines()
        file.close()
        self.list = []
        for line in lines:
            name,gpa, year = line.split( ',' )
            self.list.append( [name, eval( gpa ), eval( year )] )
        self.list.sort()

    def close( self ):
        file = open( self.fileName, 'w' )
        for name, gpa, year in self.list:
            file.write( "%s, %f, %d\n" % ( name, gpa, year ) )
        file.close()
        
    def printAll( self ):
        for name, gpa, year in self.list:
            print( "%s, %f, %d\n" % ( name, gpa, year ) )

    def append( self, name, gpa, year ):
        self.list.append(  [ name, gpa, year ]  )
        self.list.sort()

    def printSeniors( self ):
        yearGrad = 2012
        for name, gpa, year in self.list:
            if year == yearGrad:
                print( "%s, %f, %d\n" % ( name, gpa, year ) )

        
def main():
    students = Students( "smith.txt" )

    # print all the students
    students.printAll()

    # add a new student.  Alicia, 3.8, 2012
    students.append( "Alicia", 3.8, 2012 )

    # print all the seniors
    students.printSeniors()

    students.close()