Python practice [6] [database operation | file reading and writing]

Keywords: Python Database MariaDB Lambda

1. Review topics of object-oriented, file operation and database operation:

The file score.dat holds the names of 100 students and their Python lessons, advanced mathematics and English scores.

(1) define the student class, including name, Python class, advanced mathematics and English scores, total score and average score data members, and the member function is determined as required.

(2) read in the student's score and store it in the object list.

(3) find out the highest score of each subject and total score.

(4) Please rank in descending order of total score (high score first, low score last)

(5) the highest score of each subject and total score will be displayed on the screen, and the sorted report card (including total score) will be saved in the file odered_score.dat.

(6) save all student information in the file in the mariadb database;
import pymysql
import random
import os
if not os.path.exists('./score.dat'):
    with open('./score.dat','w+') as file:
        for i in range(100):
            file.write('St'+str(i)+','+','.join([str(random.randint(20,100))for j in range(3)])+'\n')

# (1) define the student class, including name, Python class, advanced mathematics and English scores, total score and average score data members, and the member function is determined as required.
class Student(object):
    def __init__(self,name,py_score,ma_score,en_score):
        self.name=name
        self.py_score = py_score
        self.ma_score = ma_score
        self.en_score = en_score
    @property
    def sum_score(self):
        return self.py_score+self.ma_score+self.en_score

    @property
    def even(self):
        return self.sum_score/3

# (2) read in the student's score and store it in the object list.
st1=Student('tom',13,23,24)
with open('./score.dat','r') as file:
    score_data=file.readlines()
    score_li=[]
    for i in score_data:
        oneData=i.rstrip('\n').split(',')
        score_li.append(Student(oneData[0],int(oneData[1]),int(oneData[2]),int(oneData[3])))

# (3) find out the highest score of each subject and total score.
py_max=max([i.py_score for i in score_li])
ma_max=max([i.py_score for i in score_li])
en_max=max([i.py_score for i in score_li])
sum_max=max([i.sum_score for i in score_li])

#(4) Please rank in descending order of total score (high score first, low score last)
score_li=sorted(score_li,key=lambda x:-x.sum_score)

# (5) the highest score of each subject and total score will be displayed on the screen, and the sorted report card (including total score) will be saved in the file odered_score.dat.

print("""
python Highest score:{0}
//The highest score of advanced mathematics course: {1}
//Maximum score of English course: {2}
//Highest total score: {3}
""".format(py_max, ma_max, en_max, sum_max))
with open('./odered_score.dat','w+') as file:
    for i in score_li:
        file.write('%s,%s,%s,%s,%s\n'%(i.name,i.py_score,i.ma_score,i.en_score,i.sum_score))
    file.seek(0,0)

# (6) save all student information in the file in the mariadb database;
## Connect to database
con = pymysql.connect(
    host='localhost',
    user='root',
    passwd='redhat',
    autocommit=True,
    charset ='utf8'
)
cur = con.cursor() # Create cursors
cur.execute('create database if not exists St_scores') # Create database
con.select_db('St_scores') # Select corresponding database
cur.execute('create table if not exists scores_data(Full name varchar(20),python float,Advanced mathematics float,English? float,Total score float)default charset=utf8') # Create table
# Read the data in the file and write to the data table
with open('./odered_score.dat') as file:
    line_data=file.readlines()
    for onedata in line_data:
        data=onedata.rstrip('\n').split(',')
        data=[data[0]]+[float(i) for i in data[1:]]
        cur.execute('insert into scores_data values("%s",%f,%f,%f,%f)'%(data[0],data[1],data[2],data[3],data[4]))

Posted by ericwright17 on Fri, 06 Dec 2019 06:45:52 -0800