You are on page 1of 19

PROGRAM – 6

TEXT FILE MANIPULATION - I


Write a menu driven program to read a text file line by line and display each word separated by a '#' and to
remove all the lines that contain the character 'a' in that file and write other lines into file.
Contents of the disp.txt
welcome to Aditya
I am learning Python
this is my school

def readfile():
myfile=open("disp.txt","r")
line=" "
while(line):
line=myfile.readline()
for word in line.split():
print(word,end='#')
print()
myfile.close()

def writefile():
f1=open("disp.txt","r")
f2=open("change.txt","w")
line=" "
while line:
line=f1.readline()
if 'a' not in line:
f2.write(line)
f1.close()
f2.close()
f2=open("change.txt","r")
line=" "
while line:
line=f2.readline()
for l in line.split():
print(l)
print()
f2.close()
while(1):
print(" Menu")
print('''1. To read a text file line by line
and display each word separated by a "#" ''')
print('''2. To remove all the lines that contain the character 'a' in the file
and write other lines into file''')
print("3. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
readfile()
elif(ch==2):
writefile()
elif(ch==3):
break
else:
print("Wrong Choice")

1
PROGRAM – 7

TEXT FILE MANIPULATION - II


Write a menu driven program in Python using function to a read a text file and
• Count number of characters
• Count number of words
• Count number of vowels
• Count number of lines
• Count number of digits
• Count number of special

characters # PROGRAM

def character(file):
cc = 0
ch='1'
while(ch):
ch = file.read(1)
cc = cc + 1
print("The number of characters are :",cc)
def words(file):
cw = 0
ch='1'
while(ch):
ch = file.readline()
wd = ch.split()
cw = cw + len(wd)
print("The number of words are :",cw)

def vowels(file):
cv = 0
ch='1'
while(ch):
ch = file.read(1)
if(ch in ('a','e','i','o','u')):
cv = cv + 1

print("The number of vowels are :",cv)


def lines(file):
cl = 0
ch='1'
while(ch):
ch = file.readline()
cl = cl + 1

print("The number of lines are",cl)


def digits(file):
cd = 0
ch='1'
while(ch):
ch = file.read(1)
if(ch.isdigit()==True):
cd = cd + 1

print("The number of digits are :",cd)

2
def spcharacter(file):
cs = 0
ch='1'
while(ch):
ch = file.read(1)
if(ch.isalnum()==False):
cs = cs + 1

print("The number of special characters are :",cs)


file = open("read.txt","r")
while(1):
print('''menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters
7. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file.seek(0,0)
character(file)
elif (ch==2):
file.seek(0,0)
words(file)
elif (ch==3):
file.seek(0,0)
vowels(file)
elif (ch==4):
file.seek(0,0)
lines(file)
elif (ch==5):
file.seek(0,0)
digits(file)
elif (ch==6):
file.seek(0,0)
spcharacter(file)
elif (ch==7):
break
else:
print('invalid input')

3
PROGRAM – 8
TEXT FILE MANIPULATION - III
Write a menu driven program in Python using function to read a text file and
• Display number of times each word appears in the file.
• Display word with maximum and minimum length
• Display words starting with uppercase

# PROGRAM

def words(file):
wdict = {}
ch='1'
while(ch):
ch = file.readline()
wd = ch.split()
for w in wd:
if(w in wdict):
wdict[w] = wdict[w] + 1
else:
wdict[w] = 1
for k,v in wdict.items():
print("The word ",k, "appears ",v, " times")

def mmword(file):
max = 0
min = 100

ch='1'
while(ch):
ch = file.readline()
wd = ch.split()
for w in wd:
if(len(w) > max):
max = len(w)
mxword = w
if(len(w)<min):
min = len(w)
mnword = w
print("The word with maximum length is : ",mxword)
print("The word with minimum length is : ",mnword)

def uword(file):
ch='1'
while(ch):
ch = file.readline()
wd = ch.split()
for w in wd:
if(w[0].isupper()):
print(w)

file = open("read.txt","r")
while(1):

4
print('''menu
1. Number of occurance of each word
2. Maximum and minimum length word
3. Word starting with uppercase
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file.seek(0,0)
words(file)
elif (ch==2):
file.seek(0,0)
mmword(file)
elif (ch==3):
file.seek(0,0)
uword(file)

elif (ch==4):
break
else:
print('invalid input')

PROGRAM – 9
BINARY FILE MANIPULATION - I
Write a menu driven program in Python using Pickle library and
 Create a binary file with following structure
o Admission number
o Student name
o Age
 Display the contents of the binary file
 Display the student whose age is above user given value
 Search a student by admission number given by

user # PROGRAM

import pickle

def writefile(file):
admno = int(input("Enter the admission number :"))
name = input("Enter the name of student :")
age = int(input("Enter the age of student "))
data = admno,name,age
pickle.dump(data,file)

def readfile(file):
while(1):
try:
data = pickle.load(file)
print(data)
except EOFError :
5
return
def above(file):
cutoff = int(input("Enter the cut off age :"))

while(1):
try:
data = pickle.load(file)
if(data[2]>=cutoff):
print(data)
except EOFError :
return
def search(file):
admno = int(input("Enter the admission number :"))
flag = 0
while(1):
try:
data = pickle.load(file)
if(data[0]==admno):
print(data)
flag = 1
return flag
except EOFError :
return flag

file = open("student.dat","ab+")
while(1):
print('''menu
1. Write binary file
2. Read biary file
3. Above given age
4. Search by admission number
5. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file.seek(0,0)
writefile(file)
elif (ch==2):
file.seek(0,0)
readfile(file)
elif (ch==3):
file.seek(0,0)
above(file)
elif (ch==4):
file.seek(0,0)
res = search(file)
if(res == 0):
print("Record not found")
elif (ch==5):
break
else:
print('invalid input')

6
PROGRAM – 10
BINARY FILE MANIPULATION - II
Write a menu driven program in Python using Pickle library and
 Create binary file with following structure
o Travelid
o From
o To
 Append data to the file
 Delete a record based on travelid
 Update a record based on travelid

# PROGRAM
import pickle
import os
def writefile(file):
trid = int(input("Enter the travel id :"))
froms = input("Enter the starting point :")
to = input("Enter the destination ")
data = trid,froms,to
pickle.dump(data,file)

def readfile(file):
while(1):
try:
data = pickle.load(file)
print(data)
except EOFError :
print("End of file")
return
def appendfile(file):
trid = int(input("Enter the travel id :"))
froms = input("Enter the starting point :")
to = input("Enter the destination ")
data = trid,froms,to
pickle.dump(data,file)

def delfile(file):
tid = int(input("Enter the travel id to delete :"))
temp = open("temp.dat","wb")
while(1):
try:
data = pickle.load(file)
if(data[0]!=tid):
pickle.dump(data,temp)
print(data)
except EOFError :
os.remove("travel.dat")
os.rename("temp.dat","travel.dat")
return
def upfile(file):
tid = int(input("Enter the travel id to update :"))
flag = 0
temp = open("temp.dat","wb")
while(1):
7
try:
data = pickle.load(file)
if(data[0]==tid):
print(data)
flag = 1
nf = input("Enter the new source: ")
nt = input("Enter the new destination")
ndata = tid,nf,nt
pickle.dump(ndata,temp)
else:
pickle.dump(data,temp)
except EOFError :
break
os.remove("travel.dat")
os.rename("temp.dat","travel.dat")
while(1):
print('''menu
1. Write binary file
2. Append data
3. Delete a record
4. Update a record
5. Display the file
6. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file = open("travel.dat","ab+")
file.seek(0,0)
writefile(file)
file.close()
elif (ch==2):
file = open("travel.dat","ab+")
file.seek(0,0)
appendfile(file)
file.close()
elif (ch==3):
file = open("travel.dat","ab+")
file.seek(0,0)
delfile(file)
file.close()
elif (ch==4):
file = open("travel.dat","ab+")
file.seek(0,0)
upfile(file)
file.close()
elif (ch==5):
file = open("travel.dat","ab+")
file.seek(0,0)
readfile(file)
file.close()
elif (ch==6):
break
else:
print('invalid input')

8
PROGRAM – 11
CSV FILE MANIPULATION
Write a menu driven program in Python to create a CSV file with following data
Roll no
o Name of student
o Mark in Sub1
o Mark in sub2
o Mark in sub3
o Mark in sub4
o Mark in sub5
Perform following operations on the CSV file after reading it.
o Calculate total and percentage for each student.
o Display the name of student if in any subject marks are greater than 80%. (Assume marks
are out of 100)

# PROGRAM
import csv
def
writefile(file):
l=[]
writer = csv.writer(file)
r = int(input("Enter the roll no :"))
n = input("Enter the name :")
s1 = int(input("Enter the marks for Subject 1:
")) s2 = int(input("Enter the marks for Subject
2: ")) s3 = int(input("Enter the marks for
Subject 3: ")) s4 = int(input("Enter the marks
for Subject 4: ")) s5 = int(input("Enter the
marks for Subject 5: ")) data =
[r,n,s1,s2,s3,s4,s5]
writer.writerow(data)

def readfile(file):
reader = csv.reader(file)
for r in reader:
print("Roll no: ",r[0])
print("Name :",r[1])
for i in range(2,7):
print("Subject ",i-1,"marks :",r[i])
total = 0
for i in range(2,7):
total = total + int(r[i])
print ("Total : ",total)
print("Percentage : ", total/5)
def read80(file):
reader = csv.reader(file)
for r in reader:
flag = 0
for i in range(2,7):
if(int(r[i])>80):
flag = 1
if(flag==1):
print("Roll no: ",r[0])
print("Name :",r[1])
for i in range(2,7):

9
print("Subject",i-1,"marks :",r[i])
file = open("travel.csv","a+")

1
writer = csv.writer(file)
writer.writerow(["Roll No", "Name", "Sub1", "Sub2", "Sub3", "Sub4" , "Sub5"])
file.close()
while(1):
print('''menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 80
4. Exit''')
ch=int(input('enter
choice')) if (ch==1):
file = open("student.csv","a+",newline='')
writefile(file)
file.close()
elif (ch==2):
file = open("student.csv","r")
file.seek(0,0)
readfile(file)
file.close()
elif (ch==3):
file = open("student.csv","r")
file.seek(0,0)
read80(file)
file.close()
elif (ch==4):
break
else:
print('invalid input')

PROGRAM – 12
LIST MANIPULATION - II
Write a python program to pass list to a function and double the odd values and half even values of a list
and display list element after changing.

# PROGRAM

def func(l):
l2 = []
for i in range(0, len(l)):
if(l[i]%2==0):
e = l[i]/2
l2.append(e)
else:
e = l[i]*2
l2.append(e)
print(l2)
a = eval(input("Enter a list: "))
func(a)

1
PROGRAM – 13
LINEAR SEARCH
Write a python program to search an element in a list and display the frequency of element present in list
and their location using Linear search by using user defined function. (List and search element should be
entered by user)

# PROGRAM

def linear(l,x):
count=0
for i in range(0,len(l)):
if(l[i]==x):
print("Found the location in the index ",i)
count+=1
print("Frequency of the element: ",count)
a = eval(input("Enter a list: "))
b = eval(input("Element to be searched: "))
linear(a,b)

PROGRAM – 14
IMPLEMENTATION OF STACK - I
Write a menu driven python program using function Push(), Pop() and Display() to implement the stack.
The program will store the name of the books.

# PROGRAM

def push(Book):
name=input("Enter the book name: ")
Book.append(name)

def pop(Book):
if Book==[]:
print("Under Flow")
else:
print("Book Deleted", Book.pop())

def display(Book):
if Book==[]:
print("Underflow!!!")
else:
print("Books in Stack")
l=len(Book)
for i in range(l-1,-1,-1):
print("<=",Book[i],end=" ")

Book=[]
while True:
print("\n1. Push\n2. Pop \n3. Display \n4. Exit")
ch=int(input("Enter your choice"))

1
if ch==1:
push(Book)
elif ch==2:
pop(Book)
elif ch==3:
display(Book)
else:
break

PROGRAM – 15
IMPLEMENTATION OF STACK - II

Write a python program using function to create the list of numeric values and search the number in the
list using Linear Search Technique. The function will return – 1 if element not found otherwise show the
position.

# PROGRAM

def search(A, x):


for i in range(len(A)):
if A[i] == x:
return i
return -1
A=[]
more = 'y'
while more == 'y' or more == 'Y':
num=eval(input("Enter a number:"))
A.append(num)
more=input("Enter more data y/n)? ")
n=eval(input("Enter a number to be search:"))
ans=search(A,n)
if ans==-1:
print("Element not found")
else:
print("Element found at position ",ans+1)

1
PROGRAM – 21
PYTHON - SQL INTERFACE - I

Write a menu driven program in Python to establish connection between Python and MySQL. Perform
following operations using the connection

 Create a store table given above (in SQL questions)


 Insert rows in the table using user given data
 Drop the attribute ‘city’ and create a new attribute of ‘pincode’.

# PROGRAM
import mysql.connector
db = mysql.connector.connect(host="localhost", user="root", password="password", database="pract",
charset="utf8")
cursor=db.cursor()

def create():
cursor.execute('''CREATE TABLE IF NOT EXISTS STORE (Storeid char(5) Primary Key, Name
varchar(20), Location varchar(20), City varchar(15), NoofEmp int, Dateofopen varchar(10), Sales int)''')

def dispstruct():
cursor.execute('''describe STORE''')
row = cursor.fetchall()
print("Column ", " Datatype", " Null", " Key", "Default", " Extra")
for c in row:
print(c[0] ," ", c[1]," ", c[2]," ", c[3]," ", c[4] ," ",c[5])

def insert():
try:
a=input('Enter storeid: ')
b=input('Enter name: ')
c=input('Enter Location: ')
d=input('Enter City: ')
e=int(input('Enter NoofEmp: '))
f= input("Enter the date of opening: ")
g = int(input('Enter sales: '))
cursor.execute('''INSERT INTO STORE VALUES (%s, %s, %s, %s, %s, %s, %s)''', (a,b,c,d,e,f,g))
print("\nSuccessfully inserted")
except:
print("error"
)
db.rollback()
return
db.commit()

def altertab():
try:
cursor.execute('''alter table STORE drop city''')
cursor.execute('''alter table STORE add pincode int(6)''')
except:
print("Column already deleted")
return

while(1):
print('''Menu

1
1. Create table

1
2. Display structure
3. Insert Records
4. Alter Table
5. Exit''')
ch=int(input('Enter choice: '))
if (ch==1):
create()
elif (ch==2):
dispstruct()
elif (ch==3):
insert()
elif (ch==4):
altertab()
elif (ch==5):
break
else:
print('Invalid Input')

PROGRAM – 22
PYTHON - SQL INTERFACE – II

Write a menu driven program in Python to establish connection between Python and MySQL. Perform
following operations using the connection using the ‘store’ table created above
 Update the pincodes for each record.
 Display the records in ascending / descending order of given column

# PROGRAM
import mysql.connector
db = mysql.connector.connect(host="localhost", user="root", password="password", database="pract",
charset="utf8")
cursor=db.cursor()
def update():
try:
cursor.execute('''select * from STORE''')
row = cursor.fetchall()
for r in row:
print("Enter the pincode for ",r[0])
p = input()
cursor.execute('''update STORE set pincode = (%s) where Storeid = (%s)''',(p,r[0]))
except:
print("Error")
db.rollback()
return
db.commit()
def dispasc():
cursor.execute('''select * from STORE order by Dateofopen''')
row = cursor.fetchall()
for r in row:
print(r)
def dispdesc():

1
cursor.execute('''select * from STORE order by Dateofopen''')
row = cursor.fetchall()
for r in row:
print(r)
while(1):
print('''menu
1. Update table
2. Display Ascending order
3. Display Descending order
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
update()
elif (ch==2):
dispasc()
elif (ch==3):
dispdesc()
elif (ch==4):
break
else:
print('invalid input')

PROGRAM – 23
PYTHON - SQL INTERFACE – III

Write a menu driven program in Python to establish connection between Python and MySQL. Perform
following operations using the connection using the ‘store’ table created above.
 Display total number of stores in each pincode
 Display the maximum sales of stores having more than 10 employees
 Display total number of employees in each pincode.

# PROGRAM
import mysql.connector
db = mysql.connector.connect(host="localhost", user="root", password="password", database="pract",
charset="utf8")
cursor=db.cursor()

def nstore():
cursor.execute('''select pincode,count(*) from STORE group by pincode''')
row = cursor.fetchall()
for r in row:
print(r)

def mxsales():
cursor.execute('''select max(Sales) from STORE where Noofemp>10''')
row = cursor.fetchall()
for r in row:
print(r)

def nemp():
cursor.execute('''select pincode,sum(Noofemp) from STORE group by pincode''')
row = cursor.fetchall()
1
for r in row:
print(r)

while(1):
print('''menu
1. Pincode wise total number of stores
2. Maximum sales (more than 10 employees)
3. Pincode wise total number of employees
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
nstore()
elif (ch==2):
mxsales()
elif (ch==3):
nemp()
elif (ch==4):
break
else:
print('invalid input')

PROGRAM – 24
PYTHON - SQL INTERFACE – IV

Write a menu driven program in Python to establish connection between Python and MySQL. Perform
following operations using the connection using the ‘store’ table created above
 Display first record
 Display next record
 Display previous record
 Display last record

# PROGRAM
import mysql.connector
db = mysql.connector.connect(host="localhost", user="root", password="password", database="pract",
charset="utf8")
cursor=db.cursor()
cursor.execute("select * from STORE")
row = cursor.fetchall()
pos=0

while(1):
print('''menu
1. First
2. Next
3. Previous
4. Last
5. Exit''')
ch=int(input('enter choice'))
if (ch==1):
pos=0
print(row[0])
1
elif (ch==2):
pos = pos + 1
print(row[pos])
elif (ch==3):
pos = pos - 1
print(row[pos])
elif (ch==4):
pos = len(row)
print(row[len(row)-1])
elif (ch==5):
break
else:
print('invalid input')

You might also like