0% found this document useful (0 votes)
58 views34 pages

MySQL Student Record Management

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views34 pages

MySQL Student Record Management

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Record Program No.

11:
PROGRAM USING MYSQL CONNECTIVITY -2
PROBLEM DEFINITION:
Write a program to connect Python with MySQL using database connectivity and perform the
following operations on data in database: Insert, Fetch, Update and Delete the data .
(i) Create a table Student with admno, sname, gender, dob, stream, average.
(ii) Insert 5 records into the student table by accepting from the user.
(iii) Increase the marks by 5 for those students who belong to science stream.
(iv) Display the number of male students who belong to commerce stream.
(v) Delete the records of those students whose average<40.

Program:
#Program using mysql connectivity

import mysql.connector
con=mysql.connector.connect(host="localhost", user="root", passwd="admin", database="sys")
if con.is_connected():
print("Connection Successful")
cur=con.cursor()

def createtable():
print("Table Creation")
cur.execute("drop table STUDENT")
cur.execute("Create Table STUDENT(admno int primary key, sname varchar(30), gender \
varchar(1), dob date, stream varchar(20), average int);")

def insertrecords():
print("Inserting Records")
n=int(input("Enter the Number of Students records:"))
for i in range(n):
adm=int(input("Enter Adm no.:"))
n=input("Name:")
g=input("Gender:(M/F?)")
DOB=input("Enter your DOB in YYYY-MM-DD format:")
s=input("Stream:")
a=input("avg")
cur.execute("Insert into STUDENT values({},'{}','{}','{}','{}',{})".format(adm,n,g,DOB,s,a))
con.commit()
cur.execute("Select * from STUDENT")
data=cur.fetchall()
print("Table - Student")
print("\n\t%-10s"%"Admno.","%-15s"%"StudentName","%-9s"%"Gender","%-25s"%"DOB",\
"%-20s"%"Stream","%-15s"%"Average")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-9s"%row[2],"%-25s"%row[3],\
"%-20s"%row[4],"%-15s"%row[5])

def update():
print("Updation of students average by 5 who belong to science stream")
cur.execute("Update STUDENT set average=average+5 where stream='scie nce'")
con.commit()
cur.execute("Select * from STUDENT")
data=cur.fetchall()
print("Table - Student")
print("\n\t%-10s"%"Admno.","%-15s"%"StudentName","%-9s"%"Gender","%-25s"%"DOB",\
"%-20s"%"Stream","%-15s"%"Average")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-9s"%row[2],"%-25s"%row[3],\
"%-20s"%row[4],"%-15s"%row[5])

def display():
print("Display of male students who belong to commerce stream")
cur.execute("Select count(*) from STUDENT where gender='M' and stream='Commerce'")
data=cur.fetchall()
print("Table - Student")
print("\n\t%-10s"%"Count of Male Students.")
for row in data:
print("\t%-10s"%row[0])

def deletion():
print("Deletion of Records")
cur.execute("Delete from STUDENT where average<40")
con.commit()
print("Table after Deletion")
cur.execute("Select * from STUDENT")
data=cur.fetchall()
print("\n\t%-10s"%"Admno.","%-15s"%"StudentName","%-9s"%"Gender","%-25s"%"DOB",\
"%-20s"%"Stream","%-15s"%"Average")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-9s"%row[2],"%-25s"%row[3],\
"%-20s"%row[4],"%-15s"%row[5])

#main program
createtable()
insertrecords()
update()
display()
deletion()
Output:

Connection Successful
Table Creation
Inserting Records
Enter the Number of Students records:3
Enter Adm no.:1001
Name:Abhijit
Gender:(M/F?)M
Enter your DOB in YYYY-MM-DD format:2000-04-28
Stream:Commerce
avg67
Enter Adm no.:1002
Name:Iraivan
Gender:(M/F?)M
Enter your DOB in YYYY-MM-DD format:2003-12-22
Stream:Science
avg56
Enter Adm no.:1003
Name:Iraivi
Gender:(M/F?)F
Enter your DOB in YYYY-MM-DD format:2003-05-11
Stream:Science
avg67
Table – Student
Admno. StudentName Gender DOB Stream Average
1001 Abhijit M 2000-04-28 Commerce 67
1002 Iraivan M 2003-12-22 Science 56
1003 Iraivi F 2003-05-11 Science 67

Updation of students average by 5 who belong to science stream


Table – Student

Admno. StudentName Gender DOB Stream Average


1001 Abhijit M 2000-04-28 Commerce 67
1002 Iraivan M 2003-12-22 Science 61
1003 Iraivi F 2003-05-11 Science 72

Display of male students who belong to commerce stream


Count of Male Students.
1
Deletion of Records
Table after Deletion

Admno. StudentName Gender DOB Stream Average


1001 Abhijit M 2000-04-28 Commerce 67
1002 Iraivan M 2003-12-22 Science 61
1003 Iraivi F 2003-05-11 Science 72
Record Program 12:
PROGRAM USING MYSQL CONNECTIVITY -3

PROBLEM DEFINITION:
Write a program to connect Python with MySQL using database connectivity and
perform thefollowing operations on data in database: Fetch, Update and Delete the
data.
(i) Create 2 tables
● Table name - Event with EventId, Eventname, NumPerformers, CelebrityID.
● Table name – Celebrity with CelebrityID, Name, Phone, FeeCharged
(ii) Insert the following records in both the tables.
Table : Event
EventId Eventname NumPerformers CelebrityID
101 Birthday 10 C102
102 Promotion Party 20 C103
103 Engagement 12 C102
104 Wedding 15 C104
105 Birthday 17 C101

Table : Celebrity
CelebrityID Name Phone FeeCharged
C101 Faiz Khan 9910195610 200000
C102 Sanjay Kumar 8934664481 250000
C103 NeeraKhan Kapoor 9811665685 300000
C104 Reena Bhatia 6587775645 100000

(iii) Display the Eventname, Name of celebrity and Feecharged for those
celebrities whocharge more than 200000
(iv) Increase the Feecharged by 10,000 for the events whose number of Performers is > 15
(v) Delete the records of those Celebrity whose name starts with R.
Program:
#Program using mysql connectivity

import mysql.connector as q
con=q.connect(host="localhost",user="root",password="admin",database="sys")
if con.is_connected():
print("Connection Successful")
cur=con.cursor()

def createtable():
print("Tables created")
cur.execute("Create Table Event (EventID int, Eventname varchar(20), NumPerformers int,
CelebrityID varchar(4))")
con.commit()
cur.execute("Create Table Celebrity (CelebrityID varchar(4), Name varchar(20), Phon numeric,
Feecharged int)")
con.commit()

def insertrecords():
print("Records Inserted")
cur.execute("Insert into Event values(101,'Birthday',10,'C102'),(102,'Promotion
Party',20,'C103'),(103,'Engagement',12,'C102'),(104,'Wedding',15,'C104'),
(105,'Birthday',17,'C101')")
con.commit()
cur.execute("Insert into Celebrity values('C101','Faiz Khan',9910193610,200000),('C102','Sanjay
Kumar',8934664491,250000),('C103','Neerakhan Kapoor',9811665685,300000),
('C104','Raveena Bhatia',6587775645,100000)")
con.commit()
cur.execute("Select * from Event")
data=cur.fetchall()
print("Table - Event")
print("\n\t%-10s"%"EventId","%-15s"%"EventName","%-25s"%"No.of Performers","%-
30s"%"CelebrityID")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-25s"%row[2],"%-30s"%row[3])
cur.execute("Select * from Celebrity")
data=cur.fetchall()
print("Table - Celebrity")
print("\n\t%-10s"%"CelebrityId","%-15s"%"CelebrityName","%-25s"%"Phone No.","%-
30s"%"Feecharged")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-25s"%row[2],"%-30s"%row[3])

def display():
print("Display of Events")
cur.execute("Select Eventname,Name,Feecharged from Event Natural Join Celebrity where
Feecharged>200000")
data=cur.fetchall()
print("\n\t%-10s"%"EventName","%-15s"%"Name","%-25s"%"Feecharged")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-25s"%row[2])

def updation():
print("Updation of Records")
cur.execute("Update Celebrity C, Event E set Feecharged=Feecharged+10000 where
Numperformers>15 and C.CelebrityID=E.CelebrityID")
con.commit()
cur.execute("Select * from Event")
data=cur.fetchall()
print("Table - Event")
print("\n\t%-10s"%"EventId","%-15s"%"EventName","%-25s"%"No.of Performers","%-
30s"%"CelebrityID")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-25s"%row[2],"%-30s"%row[3])
cur.execute("Select * from Celebrity")
data=cur.fetchall()
print("Table - Celebrity")
print("\n\t%-10s"%"CelebrityId","%-15s"%"CelebrityName","%-25s"%"Phone No.","%-
30s"%"Feecharged")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-25s"%row[2],"%-30s"%row[3])

def deletion():
print("Deleting Celebrity who's name starts with R")
cur.execute("Delete from Celebrity where Name like 'R%'")
con.commit()
cur.execute("Select * from Celebrity")
data=cur.fetchall()
print("Table - Celebrity")
print("\n\t%-10s"%"CelebrityId","%-15s"%"CelebrityName","%-25s"%"Phone No.","%-
30s"%"Feecharged")
for row in data:
print("\t%-10s"%row[0],"%-15s"%row[1],"%-25s"%row[2],"%-30s"%row[3])

#main program
createtable()
insertrecords()
display()
updation()
deletion()
Output:

Connection Successful
Tables created
Records Inserted
Table - Event

EventId EventName No.of Performers CelebrityID


101 Birthday 10 C102
102 Promotion Party 20 C103
103 Engagement 12 C102
104 Wedding 15 C104
105 Birthday 17 C101
Table - Celebrity

CelebrityId CelebrityName Phone No. Feecharged


C101 Faiz Khan 9910193610 200000
C102 Sanjay Kumar 8934664491 250000
C103 Neerakhan Kapoor 9811665685 300000
C104 Raveena Bhatia 6587775645 100000

Display of Events
EventName Name Feecharged
Birthday Sanjay Kumar 250000
Promotion Party Neerakhan Kapoor 300000
Engagement Sanjay Kumar 250000
Updation of Records
Table - Event

EventId EventName No.of Performers CelebrityID


101 Birthday 10 C102
102 Promotion Party 20 C103
103 Engagement 12 C102
104 Wedding 15 C104
105 Birthday 17 C101
Table - Celebrity

CelebrityId CelebrityName Phone No. Feecharged


C101 Faiz Khan 9910193610 210000
C102 Sanjay Kumar 8934664491 250000
C103 Neerakhan Kapoor 9811665685 310000
C104 Raveena Bhatia 6587775645 100000
Deleting Celebrity who's name starts with R
Table - Celebrity

CelebrityId CelebrityName Phone No. Feecharged


C101 Faiz Khan 9910193610 210000
C102 Sanjay Kumar 8934664491 250000
C103 Neerakhan Kapoor 9811665685 310000
Record Program 13:
PROGRAM USING MYSQL CONNECTIVITY -4

PROBLEM DEFINITION:

Write a program to connect Python with MySQL using database


connectivity andperform the following operations on data in database:
Fetch, Update and Deletethe data.

(i) Create 2 tables


● Table name - Employee with Empno, Name, Desig, Salary, Leave, Bonus.
● Table name – Insurance with Empno, LIC
(ii) Insert 5 records in both the tables by accepting the values of the
attributesfrom the user.
(iii) Display the total salary of each designation of those employees
whose namestarts with ‘R’.
(iv) Display the Employee Number and Name who has the LIC insurance of
Rs.50000.
(v) Update the salary by 10% for those employees whose designation is
Clerk.

Program:
#Program using mysql connectivity

def insertemployee():
for i in range(5):
eno=int(input("Enter the Employee number "))
ename=input("Enter the Employee name ")
desig=input("Enter the designation ")
sal=float(input("Enter the salary "))
lea=float(input("Enter the leave details "))
bon=float(input("Enter the bonus details "))
cursor.execute("insert into Employee values({0},'{1}','{2}',{3},{4},
{5})".format(eno,ename,desig,sal,lea,bon))
print("2. Records inserted for Employee table")
cursor.execute("select * from Employee")
data=cursor.fetchall()
count=cursor.rowcount
print("Rows: ",count)
print("%10s"%"Emp No.","%15s"%"EmpName","%20s"%"Desig","%15s"%"Salary",
"%20s"%"Leave","%10s"%"Bonus")
for row in data:
print("%10s"%row[0],"%15s"%row[1],"%20s"%row[2],
"%15s"%row[3],"%20s"%row[4],"%10s"%row[5])
def insertinsurance():
for i in range(5):
eno=int(input("Enter the Employee number "))
insid=int(input("Enter the Insurance ID "))
lic=int(input("Enter the LIC Amount "))
cursor.execute("insert into Insurance values({},{},{})".format(eno,insid,lic))

print("2. Records inserted for Insurance table")


cursor.execute("select * from Insurance")
data=cursor.fetchall()
count=cursor.rowcount
print("Rows: ",count)
print("%10s"%"Emp No.","%15s"%"InsuranceId","%9s"%"LICAmt")
for row in data:
print("%10s"%row[0],"%15s"%row[1],"%9s"%row[2])

def Display1():
print("3. Display the total salary of each designation of those employees whose
name starts with R")
cursor.execute("select sum(salary),desig from Employee where ename like 'R%'
group by desig")
data=cursor.fetchall()
print("Employees total salary designation wise based on the name starting with R")
print("%10s"%"Sum(Salary).","%15s"%"Designation")
for row in data:
print("%10s"%row[0],"%15s"%row[1])

def Display2():
print("4. Display the Employee Number and Name who has the LIC insurance with
the amount 50000.")
cursor.execute("select Employee.empno, ename from Employee, Insurance
where Employee.empno =Insurance.empno and lic=50000")
data=cursor.fetchall()
print("%10s"%"Emp No.","%15s"%"EmpName")
for row in data:
print("%10s"%row[0],"%15s"%row[1])

def Update():
print("5. Increase the salary by 10% for those employees whose designation is
clerk")
cursor.execute("update Employee set salary=salary*1.1 where desig='Clerk'")
cursor.execute("select * from Employee where desig='Clerk'")
data=cursor.fetchall()
print("%10s"%"Emp No.","%15s"%"EmpName","%20s"%"Desig","%15s"%"Salary",
"%20s"%"Leave","%10s"%"Bonus")
for row in data:
print("%10s"%row[0],"%15s"%row[1],"%20s"%row[2],
"%15s"%row[3],"%20s"%row[4],"%10s"%row[5])

#main program
import mysql.connector as sqlt
mycon=sqlt.connect(host="localhost",user="root",passwd="admin",database="sys")
if mycon.is_connected():
print("Successful")
cursor=mycon.cursor()
cursor.execute("drop table employee,insurance")
cursor.execute("create table Employee(empno int primary key, ename varchar(20),
desig varchar(20),salary float(8,2),lea int,bon float)")
print("1. Employee Table created")
cursor.execute("create table Insurance(empno int, InsId int primary key, lic int)")
print("1. Insurance table created")
mycon.commit()
insertemployee()
insertinsurance()
Display1()
Display2()
Update()

Output:
Record Program No. 14:

PROGRAM USING TEXT FILE -1


PROBLEM DEFINITION:
Write a Python program using functions to create a text file “Replace. txt”, read lines
from the text file “Replace.txt” and remove all the lines that contain the character 'a'
in the file and write it to another file called “New.txt”.

Program:
#Program using text file

def writetxt():
fout=open("Replace.txt","w")
rep='y'
while(rep=='y'):
s=input("Enter the line to store : ")
fout.write(s)
fout.write('\n')
rep=input("Continue ")
fout.close()

def readtxt():
fin=open("Replace.txt")
fout=open("New.txt",'w')
for line in fin:
for i in line:
if i=='a' or i=='A':
print("Writing the line on New.txt",line)
fout.write(line)
break
fin.close()
fout.close()
print("Reading from the file New.txt")
fin=open("New.txt")
for line in fin:
print(line.rstrip('\n'))
#main program
print("\t\t\t Program to read a text file Replace.txt and write on the text file
New.txt")
print("Creating text file")
writetxt()
print("Reading from the file Replace.txt")
readtxt()
Output:
Program to read a text file Replace.txt and write on the text file New.txt
Creating text file
Enter the line to store : This is a text file program
Continue y
Enter the line to store : help function is useful for beginners
Continue y
Enter the line to store : try using functions
Continue y
Enter the line to store : which is helpful
Continue y
Enter the line to store : to learn python programming
Continue y
Enter the line to store : in an efficient way
Continue n
Reading from the file Replace.txt
Writing the line on New.txt This is a text file program

Writing the line on New.txt to learn python programming

Writing the line on New.txt in an efficient way

Reading from the file New.txt


This is a text file program
to learn python programming
in an efficient way
Record Program No. 15
PROGRAM USING TEXT FILE -2
PROBLEM DEFINITION:

Write a Python program using functions to create a text file “Story.txt”, read lines from
the text file “Story.txt” and display those words whose length is less than 4 characters.

Program:
#Program using text file

def writetxt():
fout=open("Story.txt","w")
rep='y'
while(rep=='y'):
s=input("Enter the line to store : ")
fout.write(s)
fout.write('\n')
rep=input("Continue ")
fout.close()

def readtxt():
fin=open("Story.txt")
for line in fin:
n=line.split()
for i in n:
if len(i)<4:
print(i)
fin.close()
#main program
print("\t\t\t\t\t Program using text file Story.txt")
print("Creating text file")
writetxt()
print("Reading from the file")
readtxt()
Output:

Program using text file Story.txt


Creating text file
Enter the line to store : An apple a day keeps the doctor away
Continue y
Enter the line to store : Enjoy your holidays and study
Continue n
Reading from the file
An
a
day
the
and
Record Program No. 16:
PROGRAM USING TEXT FILE -3

PROBLEM DEFINITION:
Write a Python program using function to count the number of words starting with the
vowel from the file Books.txt.

Program:
#Program using text file

def writetxt():
fout=open("Books.txt","w")
rep='y'
while(rep=='y'):
s=input("Enter the line to store :")
fout.write(s)
fout.write('\n')
rep=input("Continue ")
fout.close()

def readtxt():
fin=open("Books.txt")
ct=0
for line in fin:
n=line.split()
for i in n:
if i[0]=='a' or i[0]=='e' or i[0]=='i' or i[0]=='o' or i[0]=='u' or\
i[0]=='A' or i[0]=='E' or i[0]=='I' or i[0]=='O' or i[0]=='U':
print(i)
ct+=1
fin.close()
print("No. of words starting with vowel= ",ct)
#main program
print("\t\t\t\t\t Program using text file Books.txt")
print("Creating text file")
writetxt()
print("Reading from the file")
readtxt()
Output:

Program using text file Books.txt


Creating text file
Enter the line to store: A python program to store the details in the text file and print the
number of words starting with a vowel
Continue n
Reading from the file
A
in
and
of
a
No. of words starting with vowel= 5
Record Program No. 17:
PROGRAM USING TEXT FILE -4
PROBLEM DEFINITION:
Write a Python program which has the function to read from the file Exam.txt
and display all the lines which ends with the word “health”.

Program:
#Program using text file

def wetxt():
fout=open("Exam.txt","w")
rep='y'
while(rep=='y'):
s=input("Enter the line to store :")
fout.write(s)
fout.write('\n')
rep=input("Continue ")
fout.close()

def retxt():
fin=open("Exam.txt")
for line in fin:
n=line.split()
if n[len(n)-1]=="health":
print(line)
fin.close()

#main program
print("\t\t\t\t\t Program using text file Exam.txt")
print("Creating text file")
wetxt()
print("Reading from the file")
retxt()

Output:
Program using text file Exam.txt
Creating text file
Enter the line to store: We all need good health
Continue y
Enter the line to store: We must need energy
Continue n
Reading from the file
We all need good health
Record Program No. 18:
PROGRAM USING BINARY FILE -1
PROBLEM DEFINITION:
Write an interactive menu driven Python program using binary file to perform the
following tasks:
(i) Write the information of the car like CarNo, Carname, mileage and price onto the file
“CARS.DAT”
(ii) Read from the file and display all the “Toyota cars” with their price.

Program:

#Program using binary file


import pickle
def writecar():
fout=open("Cars.dat","wb")
rep='y'
while rep=='y':
L=[]
CarNo=int(input("Enter the Car No. "))
L.append(CarNo)
Carname=input("Enter the Car Name: ")
L.append(Carname)
mileage=float(input("Enter mileage: "))
L.append(mileage)
price=float(input("Enter the price: "))
L.append(price)
pickle.dump(L,fout)
rep=input("Continue ")
fout.close()

def readcar():
fin=open("Cars.dat","rb")
try:
while True:
list1=pickle.load(fin)
for i in range(len(list1)):
if list1[1]=="Toyota":
print(list1[i], end=' ')
print()
except EOFError:
fin.close()
#main program
print("\t\t\t Program using binary file Cars.dat")
print("To write the data on to the binary file")
writecar()
print("Read from the binary file")
readcar()

Output:

Program using binary file Cars.dat


To write the data on to the binary file
Enter the Car No. 1
Enter the Car Name: Toyota
Enter mileage: 899
Enter the price: 6000000
Continue y
Enter the Car No. 2
Enter the Car Name: Maruti
Enter mileage: 455
Enter the price: 900000
Continue n
Read from the binary file
1 Toyota 899.0 6000000.0
Record Program No. 19:
PROGRAM USING BINARY FILE -2

PROBLEM DEFINITION:
Write a Python program to update the binary file “Mobile.dat” containing the information
about mobile like ModelNo, memorycard, details and megapixel. The Modelno whose
megapixel to be updated are accepted from the user.

Program:
#Program using binary file
import pickle
import sys
import os
def wmobile():
fout=open("Mobile.dat","wb")
rep='y'
while rep=='y':
L=[]
ModelNo=int(input("Model No. "))
L.append(ModelNo)
Memorycard=int(input("Size of Memory card: "))
L.append(Memorycard)
Details=input("Details about the mobile: ")
L.append(Details)
Megapixel=int(input("Megapixel: "))
L.append(Megapixel)
pickle.dump(L,fout)
rep=input("Continue ")
fout.close()

def updatemobile(mno,mp):
fin=open("Mobile.dat","rb")
fout=open("Temp.dat","wb")
pos=0
list1=[]
try:
while True:
f=0
list1=pickle.load(fin)
for i in range(len(list1)):
if list1[0]==mno:
list1[3]=mp
pickle.dump(list1,fout)
except EOFError:
fin.close()
fout.close()
os.remove("Mobile.dat")
os.rename("Temp.dat","Mobile.dat")

def readmobile():
fin1=open("Mobile.dat","rb")
list2=[]
try:
while True:
list2=pickle.load(fin1)
for i in range(len(list2)):
print(list2[i],end=' ')
print()
except EOFError:
fin1.close()
#main program
print("\t\t\t Program using binary file Mobile.dat")
print("To write the data on to the binary file")
wmobile()
print("Updating the binary file")
mn=int(input("Enter the model no to be updated :"))
mp=int(input("Enter the megapixel to be modified :"))
updatemobile(mn,mp)
print(“Reading from the updated binary file”)
readmobile()

Output:

Program using binary file Mobile.dat


To write the data on to the binary file
Model No. 1
Size of Memory card: 12
Details about the mobile: nice
Megapixel: 12
Continue y
Model No. 2
Size of Memory card: 24
Details about the mobile: handy
Megapixel: 64
Continue n
Updating the binary file
Enter the model no to be updated :2
Enter the megapixel to be modified :128
Reading from the updated binary file
1 12 nice 12
2 24 handy 128
Record Program No. 20:
PROGRAM USING BINARY FILE -3

PROBLEM DEFINITION:
Write a Python program to do the following:
(i) Write the information of the directory details like name, address,
areacode and phone number on to the binary file “Telephone.DAT”
(ii) Delete all the records where the areacode is “TP101”.
(iii) Read from the file and display the details of all the records and
also to count the number of records present in it.

Program:

#Program using binary file


import os
import pickle
def wridict():
fout=open("Telephone.dat","wb")
rep='y'
while rep=='y':
l=[]
name=input("Enter the Name: ")
l.append(name)
address=input("Enter the Address: ")
l.append(address)
areacode=input("Enter area code: ")
l.append(areacode)
phone=int(input("Enter the phone no: "))l.append(phone)
pickle.dump(l,fout)
rep=input("Continue ")
fout.close()

def deldict():
fin=open("Telephone.dat","rb")
fout=open("Temp.dat","wb")
try:
while True:
list2=pickle.load(fin)
if list2[2]!="TP101":
pickle.dump(list2,fout)
except EOFError:
fout.close()fin.close()
os.remove("Telephone.dat")
os.rename("Temp.dat","Telephone.dat")
def readdict():
fin=open("Telephone.dat","rb")
try:
while True:
list1=pickle.load(fin)
print(list1)
except EOFError:fin.close()

#main program
print("\t\t\t Program using binary file Telephone.dat")
print("To write the data on to the binary file")
wridict()
print("To delete the records with the area code TP101")
deldict()
print("Read from the binary file")
readdict()

Output:

Program using binary file Telephone.dat


To write the data on to the binary file
Enter the Name: Anand
Enter the Address: 2, Gandhi Road, Chetpet
Enter area code: TP101
Enter the phone no: 9876556789
Continue y
Enter the Name: Ashish
Enter the Address: 13, 14th main road, Anna nagar
Enter area code: TP102
Enter the phone no: 6789009876
Continue n
To delete the records with the area code TP101
Read from the binary file
['Ashish', '13, 14th main road, Anna nagar', 'TP102', 6789009876]
Record Program No. 21:
PROGRAM USING CSV FILE -1

PROBLEM DEFINITION:
Write an interactive Python program using functions to perform the writing operation onto
the csv file “Student.csv”. The details to be written are Rno, Name, Marks in 5 subjects and
Average. Read from the “Student.csv” file and display the details of those students whose
Average is above 85.

Program:

#Program using csv file


import csv
def writestud():
fields=['Rno','Name','Sub1','Sub2','Sub3','Sub4','Sub5','Average']
l=[]
n=int(input("Enter the number of students"))
with open("Student.csv","w", newline=' ') as fout:
csvwriter=csv.writer(fout)
csvwriter.writerow(fields)
for i in range(n):
rows=[]
rno=int(input("Enter the Rollno: "))
rows.append(rno)
name=input("Enter the name: ")
rows.append(name)
sub1=int(input("Enter the marks in Subject 1: "))
rows.append(sub1)
sub2=int(input("Enter the marks in Subject 2: "))
rows.append(sub2)
sub3=int(input("Enter the marks in Subject 3: "))
rows.append(sub3)
sub4=int(input("Enter the marks in Subject 4: "))
rows.append(sub4)
sub5=int(input("Enter the marks in Subject 5: "))
rows.append(sub5) avg=(sub1+sub2+sub3+sub4+sub5)//5
rows.append(avg)
l.append(rows)
csvwriter.writerows(l)

def readstud():
with open("Student.csv",newline=' ') as fin:
reader=csv.reader(fin)
ct=0l=[]
for row in reader:print(row)
l.append(row) ct+=1
print(“No. of Records”,ct-1)
print(“Students data whose average is >85”)
for i in range(1,ct):
if int(l[i][7])>85:
print(l[i])

#main program
print(“\t\t\t\t\t\t Program using CSV File Student.csv”)
print(“To Write data on the file”)
writestud()
print(“Reading from the file”)
readstud()

Output:
Program using CSV File Student.csv
To Write data on the fie
Enter the number of students 3
Enter the Rollno: 1
Enter the name: Deepa
Enter the marks in Subject 1: 44
Enter the marks in Subject 2: 55
Enter the marks in Subject 3: 66
Enter the marks in Subject 4: 77
Enter the marks in Subject 5: 88
Enter the Rollno: 2
Enter the name: Harini
Enter the marks in Subject 1: 88
Enter the marks in Subject 2: 99
Enter the marks in Subject 3: 78
Enter the marks in Subject 4: 98
Enter the marks in Subject 5: 77
Enter the Rollno: 3
Enter the name: Ranjan
Enter the marks in Subject 1: 88
Enter the marks in Subject 2: 87
Enter the marks in Subject 3: 89
Enter the marks in Subject 4: 89
Enter the marks in Subject 5: 87
Reading from the file
['Rno', 'Name', 'Sub1', 'Sub2', 'Sub3', 'Sub4', 'Sub5', 'Average']
['1', 'Deepa', '44', '55', '66', '77', '88', '66']
['2', 'Harini', '88', '99', '78', '98', '77', '88']
['3', 'Ranjan', '88', '87', '89', '89', '87', '88']
No. of Records 3
Students data whose average is >85
['2', 'Harini', '88', '99', '78', '98', '77', '88']
['3', 'Ranjan', '88', '87', '89', '89', '87', '88']
Record Program No. 22:
PROGRAM USING CSV FILE -2
PROBLEM DEFINITION:
Write a Python program using functions to write the details of Employee on to the file “Emp.csv”
which has the following: Eno, Name, Designation, Department and Salary. Read from the file and
display the Name and Salary of the “Managers” who belong to “Sales” department.

Program:

#Program using csv file


import csv
def writeemp():
fields=['Eno','Name','Desig','Dept','Salary']
l=[]
n=int(input("Enter the number of employees"))
with open("Emp.csv","w",newline=' ') as fout:
csvwriter=csv.writer(fout)
csvwriter.writerow(fields)
for i in range(n):
rows=[]
eno=int(input("Enter the Eno: "))
rows.append(eno)
name=input("Enter the name: ")
rows.append(name)
desig=input("Enter the Designation : ")
rows.append(desig)
dept=input("Enter the Department: ")
rows.append(dept)
salary=int(input("Enter the Salary: "))
rows.append(salary)
l.append(rows)
csvwriter.writerows(l)
def reademp():
with open("Emp.csv",newline=' ') as fin:
reader=csv.reader(fin)
l=[]
for row in reader:print(row)
l.append(row)
for i in range(1,ct):
if l[i][2]=="Manager" and l[i][3]=="Sales":
print("Name= ",l[i][1],"Salary= ",l[i][4])
#main program
print(“\t\t\t\t\t Program using CSV File Emp.csv”)
print(“To write data on the file”)
writeemp()
print(“Reading from file”)
reademp()
Output:
Program using CSV File Emp.csv
To write data on the file
Enter the number of employees 2
Enter the Eno: 1
Enter the name: Raja
Enter the Designation : Manager
Enter the Department: Sales
Enter the Salary: 90000
Enter the Eno: 2
Enter the name: Harsh Jain
Enter the Designation : Clerk
Enter the Department: Marketing
Enter the Salary: 9000
Reading from the file
['Eno', 'Name', 'Desig', 'Dept', 'Salary']
['1', 'Raja', 'Manager', 'Sales', '90000']
['2', 'Harsh Jain', 'Clerk', 'Marketing', '9000']
Name= Raja Salary= 90000
Record Program No. 23:
PROGRAM TO IMPLEMENT STACK -1

Write an interactive menu driven program using the following user defined
functions to perform given operations on the stack named ‘Record’:
(i) Push_record(Student) – To pass the list Student = [ ['Rahul', 12,'Delhi'],
[‘Kohli',11,'Mumbai'], ['Rohit',12,'Delhi'] ] as argument and then Push an object containing
Student name, Class and City of student who belongs to ‘Delhi’ to the stack Record and
return the contents of stack
(ii) Pop_record(Record) – To pass the stack Record [[“Rohit”,”12”,”Delhi”]
[“Rahul”,12,”Delhi”] ] and then to Pop all the objects from the stack and at last display
“Stack Empty” when there is no student record in the stack.
(iii) Display_record(Record) – To pass the stack Record and display all the objects.

Program:

#Program using stack concept


Record=list()
def isEmpty(Record):
if len(Record)==0:
return True
else:
return False

def Push_Record(Student):
if Student[2]=="Delhi":
Record.append(Student)

def Pop_Record(Record):
if isEmpty(Record):
print("Underflow")
else:
while Record!=[]:
print("Deleted Student Record",Record.pop())
else:
print("Stack Empty")

def Display_Record(Record):
x=len(Record)
print("%20s"%"Student Name","%20s"%"Class","%20s"%"City")
for i in range(x-1,-1,-1):
print("%20s"%Record[i][0],"%20s"%Record[i][1],"%20s"%Record[i][2])
#main program
ans='y'
while ans=='y':
mm=int(input("Enter 1 to Push, 2 to Pop, 3 to display"))
if mm==1:
Stud=[]
c1=input("Enter Student Name:")
Stud.append(c1)
c2=int(input("Enter Class:"))
Stud.append(c2)
c3=input("Enter City:")
Stud.append(c3)
Push_Record(Stud)
elif mm==2:
Pop_Record(Record)
elif mm==3:
Display_Record(Record)
ans=input("Continue?")

Output:

Enter 1 to Push, 2 to Pop, 3 to display 1


Enter Student Name:Ravi
Enter Class:11
Enter City:Delhi
Continue?y
Enter 1 to Push, 2 to Pop, 3 to display1
Enter Student Name:Raj
Enter Class:12
Enter City:Mumbai
Continue?y
Enter 1 to Push, 2 to Pop, 3 to display1
Enter Student Name:Aravind
Enter Class:12
Enter City:Chennai
Continue?y
Enter 1 to Push, 2 to Pop, 3 to display1
Enter Student Name:Bhadri
Enter Class:11
Enter City:Mumbai
Continue?y
Enter 1 to Push, 2 to Pop, 3 to display1
Enter Student Name:Charan
Enter Class:11
Enter City:Delhi
Continue?y
Enter 1 to Push, 2 to Pop, 3 to display3
Student Name Class City
Charan 11 Delhi
Ravi 11 Delhi
Continue?y
Enter 1 to Push, 2 to Pop, 3 to display2
Deleted Student Record ['Charan', 11, 'Delhi']
Deleted Student Record ['Ravi', 11, 'Delhi']
Stack Empty
Continue?n
Record Program No. 24:
PROGRAM TO IMPLEMENT STACK -2

PROBLEM DEFINITION:
BCCI has created a dictionary containing top players and their runs as key value pairs of a
cricket team. Write an interactive Python program using the functions Push(),
Pop_and_Display() to do the following operations:

i) Push() - Push the keys (name of the players) from the dictionary of the form
SCORE={"KAPIL":40, "SACHIN":55, "SAURAV":80, "RAHUL":35, "YUVRAJ":110, } into the
stack, where the corresponding value (runs) is greater than 49.
ii) Pop_and_Display()- To delete the Players name from the stack and display it

Program:

#Program using stack concept


import sys
top=None
def Push(stk,it):
stk.append(it)
top=len(stk)-1
print(stk)

def Pop_and_Display(stk):
if stk==[]:
print("Underflow")
else:
it=stk.pop()
if(len(stk)==0):
top=None
else:
top=len(stk)-1
print("Popped item is",it)

if stk==[]:
print("Stack empty")
else:
top=len(stk)-1
print("Contents in the stack")
for a in range(top,-1,-1):
print("-->",stk[a])
#main program
stack=[]
print("STACK MENU")
rep='y'
while rep=='y':
print("1. Push\t 2.Pop_and_Display\t 3.Exit")
choice=int(input("Enter the choice: "))
if(choice==1):
l={}
cid=input("Enter Player name")
l[cid]=int(input("Enter the runs scored"))
print("The dictionary is ", l)
for i in l:
if l[i] > 49:
print("Pushing the player name")
Push(stack,i)
elif choice==2:
Pop_and_Display(stack)
elif choice==3:
sys.exit()
else:
print(“Invalid Choice”)
Output:

STACK MENU
1. Push 2.Pop_and_Display 3.Exit
Enter the choice: 1
Enter Player name Saurav
Enter the runs scored 23
The dictionary is {'Saurav': 23}
Continue y
1. Push 2.Pop_and_Display 3.Exit
Enter the choice: 1
Enter Player name Dinesh
Enter the runs scored 89
The dictionary is {'Dinesh': 89}
Pushing the player name
['Dinesh']
Continue y
1. Push 2.Pop_and_Display 3.Exit
Enter the choice: 1
Enter Player name Karthick
Enter the runs scored 90
The dictionary is {'Karthick': 90}
Pushing the player name
['Dinesh', 'Karthick']
Continue y
1. Push 2.Pop_and_Display 3.Exit
Enter the choice: 2
Popped item is Karthick
Contents in the stack
--> Dinesh
Continue y
1. Push 2.Pop_and_Display 3.Exit
Enter the choice: 2
Popped item is Dinesh
Stack empty
Continue y
1. Push 2.Pop_and_Display 3.Exit
Enter the choice: 3

You might also like